我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分

I am trying to read from the input file then compare a specific part of a string using their substrings

本文关键字:字符串 比较 定部 然后 输入 读取 文件      更新时间:2023-10-16

假设我正在读取一个文件,然后将代码中的7483289与文件中的任何匹配项进行比较。

我运行了程序崩溃并终止的代码。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream file1;
file1.open("input.txt");
string str2 = str1.substr(12, 8); //comparing this
string str3 = "Kennedy chewe 7483289 20174893 2017"; //with this
string str4 = str2.substr(12, 8);
if (file1.is_open())
{
while (!file1.eof())
{
getline(file1, str1);
if (str2 == str4)
{
cout << "match!";
}
else
{
cout << "In line " << str1 << " there is no a match of: " << str2 << endl;
}
}
}
return 0;
}

输入文件格式


Mark      Bwalya       2436586  20146438  2014
Max       peter        7483289  20174893  2017
Lisa      Phiri        3674765  20813672  2018
Chitalu   Malama       4672762  20146437  2014
Frank     Tambo        6546727  20016367  2001
Malika    Chewe        4729208  20137346  2013
Raymod    Daka         3894782  20157835  2018
Lucy      Kalinga      5849535  20164675  2016
Jack      Kakwekwe     7548394  20143757  2014
Oka      gjriudf      6458934  20135743  2013
Emmanucle Fuka         4325673  20137578  2013
Brian     Mwale        5327834  20174673  2017
Lisa      MWeka        1895865  20013647  2001

如果 str4 不匹配,则预期输出。

In line Mark Bwalya 2436586 20146438 2014 there is no a match of 7483289

如果有匹配项,则预期退出

In line Max peter 7483289 20174893 2017 there is a match of 7483289

主要的根本原因是,您没有考虑文件中单词之间的空格。因此,str1 中的位置"12"不是整数的开头,而是大约 20。

为了使您的问题变得非常简单,您可以使用字符串流

就像您从文件中读取一样,相反,您从字符串中读取。
下面是解决方案代码:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
ifstream file1;
file1.open("input.txt");
stringstream sstr3{"Kennedy chewe 7483289 20174893 2017"}; //Key string
string key_name1, key_name2, key_num1, key_num2, key_num3;
sstr3 >> key_name1 >> key_name2 >> key_num1 >> key_num2 >> key_num3;
if(file1.is_open()) {
while(!file1.eof()) {
string str1;
getline(file1, str1); //input string
stringstream sstr2{str1};
string name1, name2, num1, num2, num3;
sstr2 >> name1 >> name2 >> num1 >> num2 >> num3;
if (num1 == key_num1) { //Comparison
cout << "match!" << endl;
}
else {
cout << "In line " << str1 << " there is no a match of: " << key_num1 << endl;
}
}
}
return 0;
}