Reputation: 967
Why I cannot initialize string with "\x"
string s = "\x"
It would be useful if I could later write:
int grade = 0;
while (cin >> grade)
if (grade < 60)
cout << "Your grade letter is F!";
else {
x = 50 - grade/10;
s = s + static_cast<string>(x);
cout << "Your grade letter is " << s << endl;
}
I prefer answer, that uses escape sequences computation for setting grade letter.
Upvotes: 1
Views: 353
Reputation: 726929
You misunderstand the way the escape sequences are processed. They are computed at compile-time, not at run time. On other words, when you write
"\x48"
it does not become a string of four characters at runtime; compiler converts it to a single-character string before the program is run.
You also misunderstand static_cast<...>
: if x
is not a std::string
, static-casting it to string will result in an error; if it is a std::string
, static-casting will have no effect.
You can create a single-character string at runtime and put a character code into its only character like this:
int grade = 83; // <<<=== 1..100
grade--;
int gradeLetter = g < 60 ? 'F' : ('A' + (100-grade)/10);
// At this point you can do the output:
cout << "Your grade is " << gradeLetter << endl;
// If you must have a string, do this:
string gradeStr(1,gradeLetter);
cout << "Your grade is " << gradeStr << endl;
Upvotes: 2
Reputation: 400029
Because the syntax forbids it. The \x
sequence in a string literal is a prefix that means "here comes the hexadecimal code for a character", but you're trying to omit the code part. That means it's not possible to parse the literal and figure out which character to put in the string.
Note that this is a compile-time thing, it has to be possible to compute the sequence of characters represented by a string literal, by just looking at the literal itself.
Upvotes: 4