字符串相等不起作用c ++

时间:2018-01-01 22:44:05

标签: c++ string compare

我一直在努力比较我从文件中读取的两个字符串,"一个" &安培; " 2"两者都有相同的词(例如盐),但它没有返回"等于"。我也使用过==但它没有任何区别。

#include <iostream>
#include <cstring> 
#include <fstream>
using namespace std;

int main (){ 

    string en[100];
    string line;

    int i=0;
    ifstream fileEn ("hey.txt");
    if (fileEn.is_open()){
        while (!fileEn.eof()){
            getline(fileEn,line);
            en[i]=line;
            i++;
        }
    }
    fileEn.close();

    string fa[100];
    string line1;

    i=0;
    ifstream fileFa ("hey1.txt");
    if (fileFa.is_open()){
        while (!fileFa.eof()){
            getline(fileFa,line1);
            fa[i]=line1;
            i++;
        }
    }
    fileFa.close(); 

    ifstream Matn("matn.txt");
    string matn[100];
    if(Matn.is_open()){    
        for(int i = 0; i < 100; ++i){
            Matn >> matn[i];
        }
    }
    Matn.close();
    string one = en[0];
    string two = matn[0];
    cout << one << "  " << two;
    if(one.compare(two) == 0){
        cout << "Equal";
    }
}

1 个答案:

答案 0 :(得分:1)

我建议在程序中添加一些调试输出:

    while (!fileEn.eof()){
        getline(fileEn,line);

        // Debugging output
        std::cout << "en[" << i << "] = '" << line << "'" << std::endl;

        en[i]=line;
        i++;
    }

    for(int i = 0; i < 100; ++i){
        Matn >> matn[i];

        // Debugging output
        std::cout << "matn[" << i << "] = '" << matn[i] << "'" << std::endl;

    }

希望您可以通过查看输出来了解问题所在。

此外,请注意while (!fileEn.eof()){ ... }的使用不正确。请参阅Why is iostream::eof inside a loop condition considered wrong?

我建议将该循环更改为:

    while (getline(fileEn,line)) {

        // Debugging output
        std::cout << "en[" << i << "] = '" << line << "'" << std::endl;

        en[i]=line;
        i++;
    }

同样,不要认为Matn >> matn[i]成功。我建议将该循环更改为:

    for(int i = 0; i < 100; ++i) {
        std::string s;
        if ( !(Matn >> s) )
        {
           // Read was not successful. Stop the loop.
           break;
        }

        matn[i] = s;

        // Debugging output
        std::cout << "matn[" << i << "] = '" << matn[i] << "'" << std::endl;

    }