问题描述
#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;
}
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;
}