简体   繁体   中英

getline won't read string from a variable. (C++)

I'm trying to make a variable store a written question which will then be written to a file however, the string is not being read by the getline and when I try to write it to the file it simply writes nothing.

#include <iostream>
#include <fstream>
#include <string> 

using namespace std;

void addquestiontofile(){
    ofstream myfile;
    // Open file to be written to.
    myfile.open("quesitons.txt",ios::ate | ios::app);

    string newquestion;
    cout << "insert new question:  \n";
    getline(cin, newquestion); // This is the problem line

    if(myfile.is_open())
    {
        myfile << newquestion;
    }
}

From the comments, it sounds like you have used cin >> variable to read from a previous line of input. This will leave the end of that previous line in the input stream's buffer, so the next call to getline() will yield an empty string.

You can clear the remainder of the line with

cin.ignore(numeric_limits<streamsize>::max(), '\n')

There is probably a trailing newline from a previous input. Try this:

while (newquestion.empty())
{
    getline(cin, newquestion);
    boost::trim(newquestion);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM