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

百般思念 提交于 2019-11-27 02:09:12

问题


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!


回答1:


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.




回答3:


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;



回答4:


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




回答5:


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




回答6:


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.



来源:https://stackoverflow.com/questions/3263323/c-read-from-istream-until-newline-but-not-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!