+ 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.

4th Aug 2025, 5:02 PM
Ashton Hively
Ashton Hively - avatar
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).
4th Aug 2025, 5:15 PM
Lisa
Lisa - avatar
+ 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
4th Aug 2025, 8:52 PM
Brian
Brian - avatar
+ 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.
4th Aug 2025, 8:19 PM
KrOW
KrOW - avatar
+ 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...
5th Aug 2025, 2:10 AM
Bob_Li
Bob_Li - avatar
+ 2
It could be done this way... string username = "name"; username = to_string(1); cout << username;
5th Aug 2025, 11:07 PM
Jan
Jan - avatar
+ 1
string username = "name" ; username = to_string(1); cout<<username ;
6th Aug 2025, 2:31 PM
Asim Farheen ✴️✴️✴️🤺👿👿
Asim  Farheen ✴️✴️✴️🤺👿👿 - avatar
0
you would do int username = 1; because i think 1 cant be in a string
4th Aug 2025, 9:05 PM
Kinda Alqassem
Kinda Alqassem - avatar
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
6th Aug 2025, 7:07 AM
RuntimeTerror
RuntimeTerror - avatar
0
My understanding is String username="name"; Username=string(1); cout<<username
6th Aug 2025, 9:18 AM
Angel Ann Petito
Angel Ann Petito - avatar