将嵌套 while 循环与 getline 一起使用时,内部 while 循环不会 运行 多次
When using a nested while loop with getline, the inner while loop won't run more than once
我正在使用 getline 从 .txt 文件中读取信息并使用该信息创建邻接图。文本文件的行数总是与每行中的条目一样多,但该数量永远未知。到目前为止,我有这个:
string title = argv[1];
ifstream myfile(title);
string line;
string word;
stringstream ss;
if (myfile.is_open())
{
while (getline(myfile,line))
{
ss << line; //this line was edited after the post, the problem //is the same.
while (getline(ss, word, ','))
{
//do some stuff to word
}
}
}
第一个while循环完成并将文件中的每一行读入line,然后每一个新行都成功读入ss。但是内层while循环只运行一次,第一次外层while循环是运行。此后,while 条件 (getline(ss,word,',')
) 为假。
测试文件中信息的格式如下:
cities,Atlanta,Boston,Boulder,Cheyenne,Chicago
Atlanta,0,-1,-1,-1,-1
Boston,-1,0,-1,-1,982
Boulder,-1,-1,0,-1,1130
Cheyenne,-1,-1,-1,0,-1
Chicago,-1,982,1130,-1,0
我真的不知道发生了什么。有什么想法吗?
您可能需要在重新使用后清理流状态。
我正在使用 getline 从 .txt 文件中读取信息并使用该信息创建邻接图。文本文件的行数总是与每行中的条目一样多,但该数量永远未知。到目前为止,我有这个:
string title = argv[1];
ifstream myfile(title);
string line;
string word;
stringstream ss;
if (myfile.is_open())
{
while (getline(myfile,line))
{
ss << line; //this line was edited after the post, the problem //is the same.
while (getline(ss, word, ','))
{
//do some stuff to word
}
}
}
第一个while循环完成并将文件中的每一行读入line,然后每一个新行都成功读入ss。但是内层while循环只运行一次,第一次外层while循环是运行。此后,while 条件 (getline(ss,word,',')
) 为假。
测试文件中信息的格式如下:
cities,Atlanta,Boston,Boulder,Cheyenne,Chicago
Atlanta,0,-1,-1,-1,-1
Boston,-1,0,-1,-1,982
Boulder,-1,-1,0,-1,1130
Cheyenne,-1,-1,-1,0,-1
Chicago,-1,982,1130,-1,0
我真的不知道发生了什么。有什么想法吗?
您可能需要在重新使用后清理流状态。