我的循环似乎有一个很大的问题。 程序的功能:程序读取文本文件,并以字符串格式给出文本文件的每一行。我想要在字符串中的数据由制表符分隔,所以我正在解析,找到标签并添加所有字符,直到我点击第一个标签。然后我将字符添加到选项卡并将其添加到数组中,以便稍后我可以评估数据。
My Inner while循环正确解析我的第一行,但没有迭代到文本文件中的下一行。
//Creates a temporary array
string current_line; //declare var line
string temp_string = "";
//When getline hits 'n' we are adding that to the string current_line
cout<<"Entering the Loop \n"<<endl;
// Gets the first line in the Text file and continutes to get each new line
// until we hit the end of file
while(getline(infile,current_line,'\n').good()){
//cout << "CURRENT SIZE " << current_line.size() << endl;
/* iterates through each character as long as the size of the current
line is greater than the counter i
*/
while(i < current_line.size()){
// If the Current character in the line is NOT a tab we add the
// character to string temp_storage
if(current_line[i] != '\t'){
temp_storage +=current_line[i];
}
/*If the Current Character in the line is a tab then we store
string temp_storage into another variable. Temp is cleared so we
can get the next word in the string
*/
else if (current_line[i] =='\t'){
Storage = temp_storage;
cout << "Current val: "<< Storage <<endl;
// Clears the temporary storage
temp_storage = "";
cout << "Clearing the temp_storage..."<< temp_storage<<endl;
}
//out << i << endl;
i++; // iterates the loop
}
cout<<"loop finished"<<endl;
}
//这是运行程序的输出
感谢阅读!
答案 0 :(得分:1)
如果你没有像流迭代器这样的“现代”东西,我会按原样使用'旧'结构。尝试for
循环。 while语句可以执行任何操作,但如果您只是使用计数器进行迭代,则for
循环更适合。
如果你这样做了,你几乎不会出错:
for ( int i=0; i<current_line.size(); i++ )
在您的代码中,i
甚至可以输入此代码部分的任何值。