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

时间:2014-10-14 17:57:22

标签: c++ string if-statement compare

我正在处理一个函数,该函数读取文件的行,直到文件中到达“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

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

首先,您应该阅读:Why is iostream::eof inside a loop condition considered wrong?

第二个调试行:

cout << line << endl;

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

修复问题后,您会看到“else语句仍然无法运行”

答案 1 :(得分:1)

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

在该环境中,从文件读取的每个字符串在其末尾都有一个\ r \ n字符。

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

您的输入文件的行似乎以&#34; \ r \ n&#34;这是Windows的标准,但unix文本文件通常以&#39; \ n&#39;终止。

更新

这是一个关于如何删除尾随回车和换行符(或者你想要的任何其他内容)的小演示:

#include <string>
#include <algorithm>
#include <iostream>

void trim_cruft(std::string& buffer)
{
    static const char cruft[] = "\n\r";

    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 world\r");      // should trim the trailing \r
    test("hello\nworld\r\n");   // don't trim the first newline
}

答案 2 :(得分:0)

正如我在评论中所说,你有两个cout语句,你应该验证哪一个正在打印XXX。如果它们都不是,那么很可能问题是字符串中有回车符,你可以用以下方法验证这个案例:

cout << line << endl; // print is here

if (line == "XXX\r")
{
    break;
}
else
{
    cout << line << endl; // print is here
    num_of_terms1++;
}
相关问题