Why does assigning an integer to a string result in blanks?

Viewed 294

I was trying to write Fizz Buzz and I came across an unexpected interaction. If I do std::cout << i, it automatically converts i (int) into a string and prints it? But if assign i to a string variable, it prints a blank instead? I managed to solve it by using std::to_string, but I was just wondering why printing to_print prints a blank instead of either an integer or throwing some sort of error?

#include <iostream>
#include <string>

int main() {
    for (int i = 1; i <= 10; i++) {
        // prints i
        std::cout << i;
    }
    
    std::cout << std::endl;
    
    for (int i = 1; i <= 10; i++) {
        std::string to_print;
        to_print = i;
        // prints blank rather than i
        std::cout << to_print;
    }
}
5 Answers

There is no string::operator=(int), but there is string::operator=(char), which is selected as the best viable candidate.

So you're assigning single characters with codes 1..10 to the string, which apparently get printed by your terminal as blanks.

Try assigning 65, it should print A.

Your variable i gets converted to a character based on its value and the ASCII table. The first few characters are not visible.

Changing your code to start iterating at 49 which is the decimal value for the character "0":

for (int i = 49; i <= 57; i++) {
    std::string to_print;
    to_print = i;
    std::cout << to_print;
}

It prints: 123456789

ASCII table is the most likely culprit. Your "string" contained control characters that aren't printed.

This happened because when you assigned the integer, the compiler treated it like a character. This is because char can be treated like a small integer.

Per asciitable.com, your string contained characters like linefeed, bell, horizontal tab, etc.

    for (int i = 1; i <= 10; i++) {
    // prints i
    std::cout << i;
    }

Here std::cout knows that it has to print int so no problem.

for (int i = 1; i <= 10; i++) {
    std::string to_print;
    to_print = i;
    // prints blank rather than i
    std::cout << to_print;
    }

Here you put an int into a std::string so it takes your number (0, 1, 2, etc.) as a char so as ASCII. Try to extend your for loop to 255 instead of 10, you will see other characters.

Like @rustyx said:

There is no string::operator=(int), but there is string::operator=(char), which is selected as the best viable candidate.

You can translate an int to std::string with to_string.

Data is stored in computer in bits. When you trying to Assign integer variable value to to a char datatype variable or String variable it will read memory contents of that variable as a bits and at printing time it will recognized as string datatype so its Look up for Ascii Value. while in case of integer printing it treat bits as a integer..

Related