简体   繁体   中英

Getline only read the first row ( or first line)

my code:

string mess;    
getline(cin,mess);

and my txt file:

hello james\n
how are \n
you.

when i am using getline. it just read in hello james. Is there a way that i can read "how are you"?

You can tell std::getline() to read up to a specific character. Assuming the character isn't in the stream, it will read the entire stream, eg

std::string mess;
if (std::getline(std::cin, mess, '\0')) {
    // ...
}
else {
    std::cout << "ERROR: failed to read input\n";
}

If you need to read in exactly two lines, you'll probably best of using std::getline() twice and combining the result, probably with an intervening "\\n" .

I am not sure if you are open for other ways to solve the problem or if you have restrictions so that you need to use getline to read the whole file. If not I find this a nifty way to put the contents of a text-file in memory to process it further.

ifstream ifs (filename, ios::in);
if (!ifs.is_open()) { // couldn't read file.. probably want to handle it.
    return;
}
string my_string((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
ifs.close();

now you should have the whole file in the variable my_string .

If you wish to read the entire file you can use the function read() (See reference here )

std::ifstream f (...);

// get length of file:
f.seekg (0, f.end);
int length = f.tellg();
f.seekg (0, f.beg);

char * buffer = new char [length];

// read data as a block:
f.read (buffer,length);

If you wish to read just those 2 lines, then its easier to use getline twice.

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