【发布时间】:2015-02-15 03:17:31
【问题描述】:
我对 C++ 还很陌生,所以如果我的术语或方法不正确,请原谅我。
我正在尝试编写一个简单的程序:
- 打开两个输入文件(“infileicd”和“infilesel”)。
- 打开单个输出文件“list.txt”。
- 逐行比较“infilesel”和“infileicd”。
- 如果在“infileicd”中找到来自“infilesel”的行,它将将该行从“infileicd”写入“list.txt”,从而有效地创建一个单独的日志文件。
我正在使用 getline() 函数来执行此操作,但在尝试比较每个文件行时遇到了麻烦。我认为如果我可以只使用感兴趣的子字符串作为比较可能会更容易。 问题是整个 getline 字符串中有多个单词,我只对第二个单词真正感兴趣。这里有两个例子:
"1529 nic1_mau_op_mode_3 "8664afm007-01" "1" 输出 1 0 逻辑 4 4136"
"1523 Pilot_mfd_only_sel "8664afm003-02" "1" 输出 1 0 逻辑 4 4112"
“nic1_mau_op_mode_3”和“pilot_mfd_only_sel”是唯一感兴趣的子字符串。
如果我只能使用第二个子字符串来比较它会容易得多,但我不知道如何专门从 getline() 函数中提取它。我没有发现任何暗示不可能做到这一点的东西,但如果不可能,那么提取该子字符串的替代方法是什么?
这是一个个人项目,所以我没有时间限制。
非常感谢您提前提供任何帮助。这是我的代码(到目前为止):
int main()
{
//Open the file to write the selected variables to.
ofstream writer("list.txt");
//Open the selected variabels file to be read.
ifstream infilesel;
infilesel.open("varsel.txt");
//Open the icd file to be read.
ifstream infileicd;
infileicd.open("aic_fdk_host.txt");
//Check icd file for errors.
if (infileicd.fail()){
cerr << "Error opening icd.\n" << endl;
return 1;
}
else {
cout << "The icd file has been opened.\n";
}
//Check selected variables file for errors.
if (infilesel.fail()){
cerr << "Error opening selection file.\n" << endl;
return 1;
}
else {
cout << "The selection file has been opened.\n";
}
//Read each infile and copy contents of icd file to the list file.
string namesel;
string nameicd;
while(!infileicd.eof()){
getline(infileicd, nameicd);
getline(infilesel, namesel);
if (nameicd != namesel){ //This is where I would like to extract and compare the two specific strings
infileicd; //Skip to next line if not the same
} else {
writer << nameicd << namesel << endl;
}
}
writer.close();
infilesel.close();
infileicd.close();
return 0;
}
【问题讨论】:
-
您是否只比较部分行,因为其他部分可能不同,但如果他们不在乎,您是否不在乎?
-
@David:正确。我只真正关心第二个子字符串。原因是两个输入文件的格式相同。
-
你能发布几行真实的行,以及你想要的数据吗?
-
@David:已添加到帖子中。
-
请放在主帖中。难以区分 cmets 中的线条。另外,请说出您要比较的文本。
标签: c++ string function compare extract