0

I've a problem with writing to file. If I write something with spaces, it write each word as a single line. Why?

void backstart()
{
    thread t1(backing);
    thread t2(thr2);
    t1.join();
    t2.join();
}

void thr2()
{
    string tmp;
    tmp = "";
    while (tmp != "/exit") 
    {
        cin >> tmp;
        if (tmp != "/exit")
        {
            writefile(tmp);
        }
    }
    runing = false;
}

void writefile(string msg)
{
    ofstream myfile("file.txt", ios::out | ios::app);
    myfile << userna + ": " + msg + ",\n";
    myfile.close();
}

Thanks Damon

Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81
Damon_Kronski
  • 17
  • 1
  • 8
  • 2
    `cin >> tmp` will split on spaces. Maybe have a look at [`getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline). – BoBTFish Oct 11 '13 at 08:06
  • THANKS THANKS THANKS! that was realy fast! Now its running perfect! I didn't know that, because I'm new in c++. ^^ – Damon_Kronski Oct 11 '13 at 08:14
  • No problem. I spelled out the read loop in full in my answer. I would recommend you don't try to learn by guesswork and random Googling; you will learn a lot of wrong things and bad practices. Maybe try a [good book](http://stackoverflow.com/q/388242/1171191). – BoBTFish Oct 11 '13 at 08:16

1 Answers1

0

Consider writing it like this:

void thr2()
{
    std::string line;
    while(std::getline(cin, line)) // this check the read succeeded as well
    {
        if (line=="/exit") break; // stop on "/exit" command
        writefile(line); // write out the line
    }
    running = false; // stop the thread, I guess
}

The most important line is

while(std::getline(std::cin, line))

which reads a whole line at a time into the std::string called line, and then checks the state of the stream to make sure the read succeeded. Read about std::getline here.

Edit:

Be very careful (and in fact I suggest just avoiding it) mixing reading with >> and getline. If you read, for example an int, with >> it will leave the '\n' character at the end of the line, so when you next read with getline, you get the rest of the line (which is basically nothing), rather than what you probably wanted, which is the next line.

If you have just read with >> and want to use getline, read into the whitespace eater first, like this std::cin >> std::ws.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76