使用比较运算符和字符串比较函数读取文本文件的子部分时出现问题

Trouble with reading a subsection of a text file using comparison operators and string compare function

本文关键字:比较 分时 问题 文件 取文本 运算符 字符串 读取 函数      更新时间:2023-10-16

因此,我正在尝试读取以下文本文件中400和*****之间的部分:

400
http://csweb.cs.wfu.edu
http://college.wfu.edu/cs/wp-content/themes/wfcollegeonepro
http://college.wfu.edu/cs/sample-page/feed
http://college.wfu.edu/cs/wp-includes/wlwmanifest.xml
http://college.wfu.edu/cs
http://www
http://www.wfu.edu
http://college.wfu.edu
http://college.wfu.edu/cs/news
*****
16331
http://college.wfu.edu/cs/wp-content/themes/wfcollegeonepro http://csweb.cs.wfu.edu
http://college.wfu.edu/cs/sample-page/feed http://csweb.cs.wfu.edu
http://college.wfu.edu/cs/wp-includes/wlwmanifest.xml http://csweb.cs.wfu.edu
http://college.wfu.edu/cs http://csweb.cs.wfu.edu
http://www http://csweb.cs.wfu.edu
http://www.wfu.edu http://csweb.cs.wfu.edu

我写了以下代码(我很确定)完成了任务:

file2.open("./cswebDataCopy2.txt");
cout << "Opening cswebData.txt file..." << endl;
if(!file2)
{
cout << "System failed to open cswebData.txt..." << endl;
}
else
{
cout << "cswebData.txt successfully opened!" << endl;
}
cout << "READING FROM: cswebData.txt" << endl;
while(!file2.eof())
{
getline(file2,line4);
//cout << line4 << endl;
if(line4=="400")
{
cout << "Number of vertices in cswebData.txt: " << line4 << endl;
continue;
}
else if(line3=="*****")
{
cout << "Found the ****** " << endl;
break;
}
else
{
cout << "Couldn't find the 400 or ***** " << endl;
}
}
cout << "Code after while loop" << endl;
file2.close();

然而,当我运行代码时,它只打印else语句中的代码,次数与文件中的行数一样多,然后打印while循环后的代码,即使文件中清楚地有400行和*****行。所以,我想我应该把正在读的行打印出来,以防任何一行被跳过。事实证明,程序正在正确读取所有行。然后,我想这可能与我在if和else-if语句中的比较方式有关。因此,我继续使用字符串比较函数重写代码,如下所示:

while(!file2.eof())
{
getline(file2,line4);
//cout << line4 << endl;
if(line4.compare("400")==0)
{
cout << "Number of vertices in cswebData.txt: " << line4 << endl;
continue;
}
else if(line4.compare("*****")==0)
{
cout << "Found the ***** " << endl;
break;
}
else
{
cout << "Couldn't find 400 or the ***** " << endl;
}
}
cout << "Code after the while loop" << endl;

然而,在运行了第二个版本的代码后,我仍然得到了与第一个版本代码相同的(错误的)结果。在这一点上,我有点困惑为什么我的代码不起作用。如果有人有独到的见解,那就太好了。谢谢

因此,问题与我的代码的任何一个版本都无关。显然,我的Sublime文本文件中有一些隐藏的字符,这些字符阻碍了文件的阅读。当我将原始文本文件的内容复制并粘贴到一个全新的文件中,然后在新的文本文件上运行两个版本的代码时,一切都如预期的那样工作。谢谢大家的投入!