How to read integers till end of line?

2019-09-07 02:14发布

I'm trying to do bfs on graph,given an adjacency list. Here's a sample input.

1 2 3
2 4
1
2 3 4

I know the number of lines,n (number of verices). Each line contains 0 to n-1 integers.

This was an attempt but it doesnt work as it reads all the integers till the end of the input.

 for(i=0;i<n;i++)
{
   while(cin>>v)
   {insert(i,v);}
}

I want to process each line separately. On searching, I found answers with vectors and stl.It would be nice if someone could come up with a more elegant solution.

Thanks.

标签: c++ input
1条回答
女痞
2楼-- · 2019-09-07 03:08

First, read a line with getline:

string line;
getline( cin, line );     // should be error handling here

Then, read the integers from the line using an istringstream:

istringstream is( line );
int n;
while( is >> n ) {
  // do something with n
}
查看更多
登录 后发表回答