如何读取整数直到行尾? [英] How to read integers till end of line?

查看:79
本文介绍了如何读取整数直到行尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于邻接表,我正在尝试在图形上执行bfs. 这是示例输入.

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

我知道行数n(顶点数). 每行包含0到n-1个整数.

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);}
}

我想分别处理每一行. 在搜索时,我发现了带有vector和stl的答案,如果有人可以提出一个更优雅的解决方案,那将是很好的.

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.

谢谢.

推荐答案

首先,使用getline读取一行:

First, read a line with getline:

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

然后,使用istringstream从行中读取整数:

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

istringstream is( line );
int n;
while( is >> n ) {
  // do something with n
}

这篇关于如何读取整数直到行尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆