当使用带有getline的嵌套while循环时,内部while循环不会运行多次

时间:2018-03-22 15:34:33

标签: c++ getline

我使用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循环完成并从文件中读取每一行到行,然后每个新行成功读入ss。但内部while循环只运行一次,第一次外部while循环运行。在此之后,while条件(getline(ss,word,','))为false。

测试文件中信息的格式如下:

  

城市,亚特兰大,波士顿,博尔德,夏延,芝加哥

     

亚特兰大,0,-1,-1,-1,-1

     

波士顿,-1,0,-1,-1,982

     

博尔德,-1,-1,0,-1,1130

     

夏延,-1,-1,-1,0,-1

     

芝加哥,-1,982,1130,-1,0

我真的不知道发生了什么。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

重新使用后,您可能必须清理流状态。

相关问题