C++ read from istream until newline (but not whitespace)

I have a std::istream which refers to matrix data, something like:

0.0 1.0 2.0
3.0 4.0 5.0

Now, in order to assess the number of columns I would like to have some code like:

std::vector<double> vec;
double x;
while( (...something...) && (istream >> x) )
{ vec.push_back(x);
}
//Here vec should contain 0.0, 1.0 and 2.0

where the ...something... part evaluates to false after I read 2.0 and istream at the point should be at 3.0 so that the next

istream >> x;

should set x equal to 3.0.

How would you achieve this result? I guess that the while condition

Thank you very much in advance for your help!

2

6 Answers

Use the peek method to check the next character:

while ((istream.peek()!='\n') && (istream>>x))
2

Read the lines into a std::string using std::getline(), then assign the string to a std::istringstream object, and extract the data from that rather than directly from istream.

1
std::vector<double> vec;
{ std::string line; std::getline( ifile, line ); std::istringstream is(line); std::copy( std::istream_iterator<double>(is), std::istream_iterator<double>(), std::back_inserter(vec) );
}
std::cout << "Input has " << vec.size() << " columns." << std::endl;
std::cout << "Read values are: ";
std::copy( vec.begin(), vec.end(), std::ostream_iterator<double>( std::cout, " " ) );
std::cout << std::endl;
3

You can use std::istream::peek() to check if the next character is a newline. See this entry in the cplusplus.com reference.

Read the number, then read one character to see if it's newline.

I had similar problem
Input is as below:

1 2
3 4 5

The 1st two were N1 and N2
Then there is a newline
then elements 3 4 5, i dont know how many these will be.

// read N1 & N2 using cin
int N1, N2;
cin >> N1;
cin >> N2;
// skip the new line which is after N2 (i.e; 2 value in 1st line)
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// now read 3 4 5 elements
int ele;
// 2nd EOF condition may required,
// depending on if you dont have last new-line, and it is end of file.
while ((cin_.peek() != '\n') && (cin_.peek() != EOF)) { cin >> ele; // do something with ele
}

This worked perfect for me.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like