This question already has answers here:
"\n" or '\n' or std::endl to std::cout? [duplicate]
(6 answers)
Closed 7 years ago.
Ok so I am working through examples thought the Bjarne's book. And I understand that single characters are delimited by single quotes, such as 'x'.
Then there are double quotes which delimit strings, such as "Hello,!"
In this book there are moment when this makes sense and times when they don't make sense.
For example:
cout << "Hello, " << first <<" << second << '\n'; //doesn't /n have single quotes?
cout << "Hello, " << first_name << " (age " << age << ")\n"; // why does /n have double quotes around it?
If anyone can explain the syntax differences between the two examples, that would greatly be appreciated.
EDIT-----------------------
cout << "Hello, " << first <<" << second << '\n'; //doesn't /n have single quotes?
Okay so /n is accounted for as a single character in the first example and as two in the second....... ) + /n
My follow up question is with the first example. If the single quotes delimit the /n. Why is there only 3 sets of ""s? Shouldn't it be like this:
<
The compiler recognizes the sequence \n in a character (or string) literal as a single character, a newline. That's why it can be used in single quotes as a character literal.
In the second line, the newline is inside double quotes because it's not a single character literal, it's a string containing the characters ) and \n (plus the string terminator).
The difference is, that 'x' is a char and "x" is a c-string (const char*) of length 2 (the character x and the null). In your example, this makes no difference because the ostream operator<< can handle both, char and const char*, but for c-functions like strlen, strcmp and so on, this makes a huge difference if you're passing a single char or a string with only one char in it (and the nullterminator).
\n is considered one character, even though it is two. It is short for creating a new line. You can also use the endl; command. I think it is easier and looks nicer in the code.
It is in double quotes in this situation because it is including more than one character with the ). In a normal situation the \n could be put in singles '' or doubles "".
*Note you can only use endl; if you have declared you are using namespace std;
Otherwise it is std::endl;
Related
given:
string element = "hello";
I would like to have the following printed:
"hello" //with quotation marks
I found how to print words with quotation marks using \"hello\", but I would like to use my variable name element to print out "hello".
The closest you can get to have
string element = "hello";
std::cout << element
and have it print
"hello"
is to use std::quoted That would make the code
string element = "hello";
std::cout << std::quoted(element);
and it would output
"hello"
Do note that std::quoted does more then just add the out quotes. If your string contains quotes then it will modify those and add a \ in from of them. That means
string element = "hello \"there\" bob";
std::cout << std::quoted(element);
will print
"hello \"there\" bob"
instead of
"hello "there" bob"
use forward slash in front of quotation marks
std::cout << "\"" << element << "\"" << std::endl;
if you want to have quotation mark inside your string,
assign the variable with quotation mark with forward slash
string element = "\"hello\"";
You'll have to write the quotation marks and the variable extra, like
std::cout << '\"' << element << '\"';
BTW: in contrast to a string literal like "\"", where you have to escape double quotes, by using a character literal, you can get away without escaping: So the following is valid as well:
std::cout << '"' << element << '"';
string element = "\"hello\"";
std::cout << element;
Why does my C++ program create the strange character shown below in the pictures? The picture on the left with the black background is from the terminal. The picture on the right with the white background is from the output file. Before, it was a "\v" now it changes to some sort of astrological symbol or symbol to denote males. 0_o This makes no sense to me. What am I missing? How can I have my program output just a backslash v?
Please see my code below:
// SplitActivitiesFoo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string s = "foo:bar-this-is-more_text#\venus \"some more text here to read.\"";
vector<string> first_part;
fstream outfile;
outfile.open("out.foobar");
for (int i = 0; i < s.size(); ++i){
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
return 0;
}
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.This is because in the actual program the string will be read in from a file and parsed then sent to another function. I guess I could figure out a way to programmatically add backslashes...
How can I have my program output just a backslash v?
If you want a backslash, then you need to escape it: "#\\venus".
This is required because a backslash denotes that the next character should be interpreted as something special (note that you were already using this when you wanted double-quotes). So the compiler has no way of knowing you actually wanted a backslash unless you tell it.
A literal backslash character therefore has the syntax \\. This is the case in both string literals ("\\") and character literals ('\\').
Why does my C++ program create the strange character shown below in the picture?
Your string contains the \v control character (vertical tab), and the way it's displayed is dependent on your terminal and font. It looks like your terminal is using symbols from the traditional MSDOS code page.
I found an image for you here, which shows exactly that symbol for the vertical tab (vt) entry at value 11 (0x0b):
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.
Well, I just saw you add the above part to your question. Now you're in difficult territory. Because your string literal does not actually contain the character v or any backslashes. It only appears that way in code. As already said, the compiler has interpreted those characters and substituted them for you.
If you insist on printing v instead of a vertical tab for some crazy reason that is hopefully not related to an XY Problem, then you can construct a lookup-table for every character and then replace undesirables with something else:
char lookup[256];
std::iota( lookup, lookup + 256, 0 ); // Using iota from <numeric>
lookup['\v'] = 'v';
for (int i = 0; i < s.size(); ++i)
{
cout << "s[" << i << "]: " << lookup[s[i]] << endl;
outfile << lookup[s[i]] << endl;
}
Now, this won't print the backslashes. To undo the string further check out std::iscntrl. It's locale-dependent, but you could utilise it. Or just something naive like:
const char *lookup[256] = { 0 };
s['\f'] = "\\f";
s['\n'] = "\\n";
s['\r'] = "\\r";
s['\t'] = "\\t";
s['\v'] = "\\v";
s['\"'] = "\\\"";
// Maybe add other controls such as 0x0E => "\\x0e" ...
for (int i = 0; i < s.size(); ++i)
{
const char * x = lookup[s[i]];
if( x ) {
cout << "s[" << i << "]: " << x << endl;
outfile << x << endl;
} else {
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
}
Be aware there is no way to correctly reconstruct the escaped string as it originally appeared in code, because there are multiple ways to escape characters. Including ordinary characters.
Most likely the terminal that you are using cannot decipher the vertical space code "\v", thus printing something else. On my terminal it prints:
foo:bar-this-is-more_text#
enus "some more text here to read."
To print the "\v" change or code to:
String s = "foo:bar-this-is-more_text#\\venus \"some more text here to read.\"";
What am I missing? How can I have my program output just a backslash v?
You are escaping the letter v. To print backslash and v, escape the backslash.
That is, print double backslash and a v.
\\v
About the Program
The program takes a number the user entered and outputs that number doubled. I created two functions, one that gathers the number (getnumber), and another that doubles it (doublenumber). The program does work properly; however, the output is not completely accurate.
The Problem
The output is only right partially. I.e the user enters 50, the value is doubled and the output should be 100. Instead, the value outputs as 100114. Only the first few numbers seem to be what I want.
Source Code:
#include <iostream>
void doublenumber(int&);
void getnumber(int&);
int main() {
int value;
getnumber(value);
doublenumber(value);
std::cin.get();
std::cin.get();
return 0;
}
void doublenumber(int &refvar) {
refvar*= 2;
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
}
void getnumber(int &userNum) {
std::cout << "\nEnter a number to double: ";
std::cin >> userNum;
}
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
^^^^^
|
multicharacter literal
It's a multicharacter literal, and has a type of int.
C++11 §2.13.2 Character literals
A character literal is one or more characters enclosed in single quotes, as in ’x’, optionally preceded by the letter L, as in L’x’. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.
Check out this post: Why does this code with '1234' compile in C++?.
I have answered my own question after carefully looking over the code. Ugh! A very simple mistake at:
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
The "'.\n'" should be: ".\n";" instead. Could someone tell me why this produced this output though?
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
C++ cin whitespace question
I'm having problem trying to understand this piece of code. I'd like to apologize if this question has already been answered but I didn't find it anywhere. I'm a beginner and its a very basic code. The problem is >> operator stops reading when the first white space
character is encountered but why is it in this case it outputs the complete input string even if we have white spaces in our string. It outputs every word of the string in separate lines. How is it that cin>>x can take input even after the white space? Plz help me out with the functioning of this code. Thanks in advance.
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::endl;
int main()
{
string s;
while (cin >> s)
cout << s << endl;
return 0;
}
The problem is >> operator stops reading when the first white space
character is encountered but why is it in this case it outputs the
complete input string even if we have white spaces in our string
Because you're using it in a loop. So each time around cin eats a word which you print and discards whitespace. The fact that you're printing a newline after each word means you don't expect to see whitespace - and in fact s contains none.
A simple way to test this would be to print:
cout << s << "$";
However the most interesting characteristic of the code is how the while tests the istream returned by << which in a boolean context yields exactly what you want: whether the input is done or not.
Using the input operator on a stream by default stops at whitespace, and skip leading whitespace. So since you reading in a loop, it skips whitespace while reading all "words" you input, and then print it inside the loop with a trailing newline.
You probably ignored the fact that whenever you are entering a new string ( after a white space character i.e. a newline, tab or blank-space ) it is being re-assigned to string s in the while loop condition. To verify this you can simply do something like :
int i=1;
while (cin >> s)
cout << i++ << ": " << s << endl;
instead of :
while (cin >> s)
cout << s << endl;
Run this and everything would be crystal clear :)
I have a string whose last part(suffix) needs to be changed several times and I need to generate new strings. I am trying to use ostringstream to do this as I think, using streams will be faster than string concatenations. But when the previous suffix is greater than the later one, it gets messed up. The stream strips off null characters too.
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
ostringstream os;
streampos pos;
os << "Hello ";
pos = os.tellp();
os << "Universe";
os.seekp(pos);
cout<< os.str() << endl;
os << "World\0";
cout<< os.str().c_str() << endl;
return 0;
}
Output
Hello Universe
Hello Worldrse
But I want Hello World. How do I do this? Is there anyother way to do this in a faster manner?
Edit:
Appending std::ends works. But wondering how it works internally. Also like to know if there are faster ways to do the same.
The string "World" is already null-terminated. That's how C strings work. "World\0" has two \0 characters. Therefore, operator<<(ostream&, const char*) will treat them the same, and copy all characters up to \0. You can see this even more clearly, if you try os << "World\0!". The ! will not be copied at all, since operator<< stopped at the first \0.
So, it's not ostringstream. It's how C strings aka const char* work.
It doesn't strip anything. All string literals in C++ are terminated by NUL, so by inserting one manually you just finish the string, as far as anyone processing it is concerned. Use ostream::write or ostream::put, if you need to do that — anything that expects char* (with no additional argument for size) will most likely treat it specially.
os.write("World\0", 6);
Why do you think a stream operation is faster than a string? And why build the string before outputting to cout?
If you want a prefix to your output you could just do it like this
const std::string prefix = "Hello ";
std::cout << prefix << "Universe" << std::endl;
std::cout << prefix << "World" << std::endl;