如何比较两个字符串?这是我的代码,它没有给出预期的结果它没有正确比较

问题描述

我的代码是关于查找names.txt中是否存在特定名称

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ifstream file("names.txt");
    string names[6];
    string test;
    cin>>test;
    for(int i=0;i<6;i++)
    {
        getline(file,names[i]);
    }
    for(int i=0;i<6;i++)
    {
        if(names[i]==test)
        {
            cout<<"found";
            return 0;
        }

    }
    cout<<"not found";
    return 0;
}

这里,在我的代码 names.txt 中包含 6 个名称

john walker
rick jo
steaven fedrer
anil kumar
raju rastogi
priyanka raj

但是当我输入 name.txt 中存在的名称时,它也会显示“未找到”(我正在输入全名)。为什么? 我哪里出错了?

解决方法

C++ std::cin 会一直读取到下一个空格,因此在您的代码中只会读取名字。您可以使用 std::getline(std::cin,test) 解决此问题。

,

你不应该使用带有字符串的cin,尝试使用 getline(cin,test);

,

我已经编辑了您的源代码,现在可以使用了。

#include <iostream>
#include <fstream>
#include <string>

int main(int argc,char*argv[])
{
    std::ifstream file("names.txt");
    
    std::string names[6];
    std::string test;
    
    std::getline(std::cin,test);
    
    for (int i = 0; i < 6; i++)
    {
        std::getline(file,names[i]);
    }

    for (int i = 0; i < 6; i++)
    {
        if (!names[i].compare(test))
        {
            std::cout << "found";
            return 0;
        }

    }
    
    std::cout << "not found";

    return 0;
}