Suppose I want to read line a of integers from input like this:
1 2 3 4 5\n
I want cin to stop at '\n' character but cin doesn't seem to recognize it.
Below is what I used.
vector<int> getclause() { char c; vector<int> cl; while ( cin >> c && c!='\n') { cl.push_back(c); cin>>c; } return cl; }
How should I modify this so that cin stop when it see the '\n' character?
cin is whitespace delimited, so any whitespace (including \n ) will be discarded. Thus, c will never be \n .
cin. ignore(80, '\n'); skips 80 characters or skips to the beginning of the next line depending on whether a newline character is encountered before 80 characters are skipped (read and discarded).
ignore() to ignore any newlines left from std::cin .
Using cin. You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.
Use getline and istringstream:
#include <sstream> /*....*/ vector<int> getclause() { char c; vector<int> cl; std::string line; std::getline(cin, line); std::istringstream iss(line); while ( iss >> c) { cl.push_back(c); } return cl; }
You can use the getline method to first get the line, then use istringstream to get formatted input from the line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With