从 txt 文件读取行后字符串比较失败
string compare failing after reading line from txt file
我正在尝试逐行读取文件并将其与代码中的字符串进行比较。但不知何故,下面的代码没有给出预期的结果。我不明白我在比较过程中遗漏了什么:
代码
int main(int argc, char** argv)
{
std::string filePath="E:\data\stopfile.txt";
std::string line;
std::ifstream myfile;
std::string test="ball";
myfile.open(filePath.c_str());
if(myfile.is_open()){
while(getline(myfile,line)){
std::cout<<line<<std::endl;
if(!line.compare(test)){
std::cout<<"SUCCESS"<<std::endl;
}
else{
std::cout<<"FAIL"<<std::endl;
}
}
}
myfile.close();
if(!test.compare("ball")){
std::cout<<"SUCCESS"<<std::endl;
}
}
输出
apple
FAIL
ball
FAIL
cat
FAIL
SUCCESS
我希望程序在 "ball" 行之后打印 SUCCESS。但是比较起来好像没有成功。
我也试过
的比较条件
if(!line.compare(test.c_str())){
结果还是一样。
您选择的行尾似乎不适合您的平台。如果我不控制文件的来源,我会经常 trim() 使用这样的函数读取数据:
const char* ws = " \t\n\r\f\v";
// trim from end (right)
inline std::string& rtrim(std::string& s, const char* t = ws)
{
s.erase(s.find_last_not_of(t) + 1);
return s;
}
// trim from beginning (left)
inline std::string& ltrim(std::string& s, const char* t = ws)
{
s.erase(0, s.find_first_not_of(t));
return s;
}
// trim from both ends (left & right)
inline std::string& trim(std::string& s, const char* t = ws)
{
return ltrim(rtrim(s, t), t);
}
// ...
while(getline(myfile,line))
{
trim(line);
// ...
}
我正在尝试逐行读取文件并将其与代码中的字符串进行比较。但不知何故,下面的代码没有给出预期的结果。我不明白我在比较过程中遗漏了什么:
代码
int main(int argc, char** argv)
{
std::string filePath="E:\data\stopfile.txt";
std::string line;
std::ifstream myfile;
std::string test="ball";
myfile.open(filePath.c_str());
if(myfile.is_open()){
while(getline(myfile,line)){
std::cout<<line<<std::endl;
if(!line.compare(test)){
std::cout<<"SUCCESS"<<std::endl;
}
else{
std::cout<<"FAIL"<<std::endl;
}
}
}
myfile.close();
if(!test.compare("ball")){
std::cout<<"SUCCESS"<<std::endl;
}
}
输出
apple
FAIL
ball
FAIL
cat
FAIL
SUCCESS
我希望程序在 "ball" 行之后打印 SUCCESS。但是比较起来好像没有成功。
我也试过
的比较条件if(!line.compare(test.c_str())){
结果还是一样。
您选择的行尾似乎不适合您的平台。如果我不控制文件的来源,我会经常 trim() 使用这样的函数读取数据:
const char* ws = " \t\n\r\f\v";
// trim from end (right)
inline std::string& rtrim(std::string& s, const char* t = ws)
{
s.erase(s.find_last_not_of(t) + 1);
return s;
}
// trim from beginning (left)
inline std::string& ltrim(std::string& s, const char* t = ws)
{
s.erase(0, s.find_first_not_of(t));
return s;
}
// trim from both ends (left & right)
inline std::string& trim(std::string& s, const char* t = ws)
{
return ltrim(rtrim(s, t), t);
}
// ...
while(getline(myfile,line))
{
trim(line);
// ...
}