Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tell cin to stop reading at newline

Tags:

c++

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?

like image 415
Mark Avatar asked Mar 12 '12 19:03

Mark


People also ask

Does CIN stop at newline?

cin is whitespace delimited, so any whitespace (including \n ) will be discarded. Thus, c will never be \n .

How do you ignore a new line in C++?

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).

How do you make a CIN not skip a line?

ignore() to ignore any newlines left from std::cin .

Where does Cin stop reading?

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.


2 Answers

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; } 
like image 165
mfontanini Avatar answered Sep 28 '22 04:09

mfontanini


You can use the getline method to first get the line, then use istringstream to get formatted input from the line.

like image 28
Geoffroy Avatar answered Sep 28 '22 04:09

Geoffroy