+ 1
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.
9 Risposte
+ 4
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).
+ 4
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
+ 2
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.
+ 2
you declared a string variable.
then you assign an int to it. this will raise an error.
maybe you should assign a string instead?
username = "1";
or if you want to input a new value instead:
cin >> username;
i am unclear on what you're trying to do...
+ 2
It could be done this way...
string username = "name";
username = to_string(1);
cout << username;
+ 1
string username = "name" ;
username = to_string(1);
cout<<username ;
0
you would do
int username = 1;
because i think 1 cant be in a string
0
Jan method is modern but note that it raises a runtime error if there's at least a non digit in the string sequence
but on the other side, your question description makes no sense
0
My understanding is
String username="name";
Username=string(1);
cout<<username