C++if语句比较字符串不起作用

C++ if statement comparing strings not working

本文关键字:不起作用 字符串 比较 语句 C++if      更新时间:2023-10-16

我正在开发一个函数,该函数读取文件的行,直到到达文件中的行"XXX",并且计数器跟踪读取了多少行。然后程序计算文件中剩余的行数。我使用if语句来确定何时中断while循环(当行读取等于"XXX"时),并且不满足条件。即使在line=="XXX"时,else语句仍将运行。我的代码出了什么问题?谢谢

#include <string>
#include <iostream>
#include <fstream>
using std::string;
using std::endl;
using std::cout;
using std::ifstream;
int main()
{ 
    //Main function
}
void read_file(string input_file_name)
{
    string i_filename = input_file_name;
    ifstream infile;
    infile.open (i_filename);
    string line;
    int num_of_terms1 = 0;
    int num_of_terms2 = 0;
    if (!infile)
    {
        cout << "Your input file could not be opened."<<endl;
    }
    else
    {
        while (!infile.eof())
        {
            getline(infile, line);
            cout << line << endl;
            if (line == "XXX")
            {
                break;
            }
            else
            {
                cout << line << endl;
                num_of_terms1++;
            }
        }
        while (!infile.eof())
        {
            getline(infile, line);
            cout << line << endl;
            num_of_terms2++;
        }
    }
cout << "Terms 1: "<<num_of_terms1 <<endl;
cout << "Terms 2: "<< num_of_terms2 <<endl;
infile.close();
}

下面是一个示例输入文件inputfile.txt:

-2 3
4 2
XXX
-2 3

提前感谢您的帮助!

我在www.compileonline.com上测试了这段代码,并重复了您的发现。

在这种环境中,从文件中读取的每个字符串的末尾都有一个字符。

当我将终止行更改为if (line == "XXXr")时,代码按预期工作。

输入文件的行似乎以"\r\n"结尾,这是windows的标准,但unix文本文件通常以"\n"结尾。

更新:

以下是一个小演示,演示如何删除拖尾回车和换行(或任何其他您想要的内容):

#include <string>
#include <algorithm>
#include <iostream>
void trim_cruft(std::string& buffer)
{
    static const char cruft[] = "nr";
    buffer.erase(buffer.find_last_not_of(cruft) + 1);
}
void test(std::string s)
{
    std::cout << "=== testing ===n";
    trim_cruft(s);
    std::cout << s << 'n';
}
int main()
{
    test("");                   // empty string
    test("hello worldr");      // should trim the trailing r
    test("hellonworldrn");   // don't trim the first newline
}

首先,您应该阅读以下内容:为什么循环条件中的iostream::eof被认为是错误的?

第二条调试线:

cout << line << endl;

在这两种情况下完全相同——您在else语句中,或者您在计算num_of_terms2,这很令人困惑。更改它们,这样您就可以看到打印的是哪一个。

修复这些问题后,您将看到"else语句将不会继续运行"

正如我在评论中所说,您有两个cout语句,您应该验证哪一个正在打印XXX。如果它们都不是,那么问题很可能是字符串中有回车,您可以使用验证其他情况

cout << line << endl; // print is here
if (line == "XXXr")
{
    break;
}
else
{
    cout << line << endl; // print is here
    num_of_terms1++;
}