Domanda

I am trying to write to a file and am having trouble with the string not writing.

From what I have been able to figure out, my string will only print if I place a '\n' after it. The problem is I am trying to write it to a file and it has to be all in line with other information.

Sample of what I am trying to make my file look like:

1111 Last, First   10     20      $30.00

What it actually writes:

1111               10     20      $30.00

This is what i have tried and it will only print the last 3 items. If I place a '\n' after getName() then it prints everything fine:

    ofstream outputFile("somefile.txt");
    outputFile << std::setw(10) << getAccount() 
               << std::setw(10) << getName() // returns a string
               << std::setw(10) << getNum1()
               << std::setw(10) << getNum2()
               << std::setw(10) << getTotal() << endl;

I have tried calling flush after getName() but it did not work

    outputFile.flush()

I am supposed to store the last and first name separately.

    string getName() const
    {
        string full = last + ", " + first;
        return full;
    }
È stato utile?

Soluzione

I'm assuming you actually specify a name for the output file, e.g.

std::ofstream outputFile("some-file.txt");

Assuming this is sorted, have a look at std::setw(n) from <iomanip> and make sure your outputs are somehow separated. For example, you might want to use

outputFile << std::setw(8) << getAccount() << ' '
           << std::setw(20) << getName() << ' '
           << std::setw(6) << getNum1() << ' '
           << std::setw(6) << getNum2() << ' '
           << getTotal() << '\n';

... and if you really want to make sure the output is immediately written to the file rather than buffered:

outputFile << std::flush;

(which is equivalent to std::outputFile.flush(); but using cuter syntax).

Based on comments mentioned above, I would guess you ended up with names containing a '\r' right at the end: this way, it looks as if there is nothing but actually the characters are just overwritten by characters coming later. You can remove the carriage return characters using

str.erase(std::remove(str.begin(), str.end(), '\r'), str.end());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top