我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
I am trying to read from the input file then compare a specific part of a string using their substrings
假设我正在读取一个文件,然后将代码中的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;
}
相关文章:
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 字符串比较中的意外输出
- 如何执行不区分大小写的字符串比较?
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- <<运算符优先级与字符串比较
- ">"运算符和"<"运算符如何进行字符串比较?
- Qt C++11 字符串通过子字符串比较列出交集
- std::out_of_range字符串比较中的异常
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 字符* 与uint8_t的字符串比较
- 用字符串 c++ 比较对向量的元素
- 使用循环进行词典字符串比较
- 如何为C++映射创建自己的字符串比较对象
- 不带比较()的字符串比较
- 与 IF 语句C++的字符串比较?
- 字符串比较在与变量一起使用时给出不同的输出
- 更快的字符串比较排序,用于唯一()
- C 字符串比较“祝您好运”&gt;“再见”
- C 奇怪的行为和字符串比较
- 子字符串与 std::memcmp 或字符串::比较的比较