0
Changing String Variables into int in C++
I was trying to change a variable called username in my code. This is what it looked like: string username = "name"; username = 1; cout<<username; And once I ran that code, it had an output of a ? in a box. I am wondering how to fix it, not what the ? in a box means.
3 Respostas
+ 2
What output were you expecting?
⍰ indicates that the character cannot be displayed by the character set you are using.
Despite it being supposed to raise a compilation error, it doesn't output anything for me on Sololearn playground (Android).
0
The compiler will try ti cast an int to char then create a string from latter.
In practice, assigning an int to string will create first a char having the int ascii code the will be created a string with that char.
0
Ashton Hively what I think you are asking is how to make cout show what you assigned to the string. The int value 1 is stored there, and you want it to display as 1 instead of the nonprintable ASCII character 1.
Here is how: cast it as an (int) in the cout stream.
cout<<(int)username;
Well... not quite right. That fails, too. Since a string object has an array of characters, it stores your assigned value of 1 inside the array. You have to pull the stored value from its index location of 0.
cout<<(int)username[0];
That works. Output: 1