Search code examples
c++stringfstream

fstream not creating text file


It seems when I try to run this source of code, instead of making an Attempt1.txt, or Attempt2.txt, or Attempt3.txt, it simply just makes a FILE named Attempt.

    string str;
    int num_attempts_x_million = 1;

    str = "Attempt";
    str += num_attempts_x_million;
    str += ".txt";
    textfile.open(str); 
    textfile << password << endl;
    textfile.close();

Solution

  • You might be appending control characters, not 'regular' characters. This is assuming, of course, that the type of num_attempts_x_million is an int (or any integer type).

    std::string::operator+= does not have an overload for int. Instead, it has one for char so it casts it into a char first and then appends it. For low integer values, this ends up with things like 0x0, 0x1, 0x2, etc which are known as control characters in ASCII.

    In order for you to convert the integer into a string you have to use std::to_string.