如果条件 C++,如何跳过下一行

how to skip the next line if condition c++

本文关键字:一行 何跳过 条件 C++ 如果      更新时间:2023-10-16

我看了一下其他例子,但我无法使这个工作。 我有一个文件在某些时候有奇怪的字符,例如:"Äèîpg" 我不想保存这一行,因为似乎带有 getline 的循环将停在那里(它存储直到带有垃圾箱的行(。请问我该怎么做?我知道当这种情况发生时:"key =0",下一行将有这些字符"Äèîpg"。

这是我的代码:

file = "example.log";
ifstream f(file);
f.open(file);
if (f.good()){
while (getline(f, line)) {
lineNumber++;
if ((lineNumber>= line1 - 20) && (lineNumber<= line2)){
pos = line.find("key = 0");
if (pos != string::npos){
std::cout << "skip the line" << endl;
}
else{
Type v;
v.line= line;
v.index = lineNumber;
linesVector.push_back(v);
}
}
}
} 
f.close(); 

然后我创建一个包含所需信息的剪切文件:

ofstream myfile;    
string merge =  file + "_Cut.log";  
myfile.open(merge);     
for (unsigned int i = 0; i < linesVector.size(); i++){      
myfile << linesVector[i].line << "n";      
//std::cout << linesVector[i].line << endl;     
}   
myfile.close();

提前感谢您的帮助!

为了弄清楚我的文件是什么样子的,这里是原始的"示例.log" (我不能把它附在某个地方(。

2017-08-03 09:38:46 Expeum im6
2017-08-03 09:38:46 nubla4
2017-08-03 09:38:46 blaze
2017-08-03 09:38:46 ue
2017-08-03 09:38:46 er
2017-08-03 09:38:46 key = 0
2017-08-03 09:38:46 Q2žl2pE&ö³„Ôï¬ÈL+g…^cÎ1áø/7E›¸¥ü‰úLÎ’Æ
2017-08-03 09:38:46 81B9CEandrew499OEE4MUI5Q0VhbmRyZXc0OTk=
2017-08-03 09:38:47 B9CEandrew499OEE4MUI5Q0VhbmRyZXc0OTk=
2017-08-03 09:38:48 bla
2017-08-03 09:38:49 OK
2017-08-03 09:50:12  key = 0
2017-08-03 09:50:12 E&ö³„Ôï¬ÈL+g…^cÎ1áø/7E›¸¥ü‰úLÎ’Æ

这是我在剪切文件中得到的:

2017-08-03 09:38:46 Expeum im6
2017-08-03 09:38:46 nubla4
2017-08-03 09:38:46 blaze
2017-08-03 09:38:46 ue
2017-08-03 09:38:46 er
2017-08-03 09:38:46 key = 0
2017-08-03 09:38:46 Q2žl2p

问题是它被困在最后的吉伯里什,无法继续前进! 会不会是缺少了一些回车?我的想法快用完了。

所以看起来你试图扔掉"key = 0"一行和下一行?

如果是这样,您可以在嵌套的if-语句中使用ignore,如下所示:f.ignore(numeric_limits<std::streamsize>::max(), 'n')

如果lineNumber应该将其视为一行,您还需要添加++lineNumber

如果这可能是文件中的最后一行,则应总共添加以下代码:

if(!f.ignore(numeric_limits<std::streamsize>::max(), 'n')) {
break;
}
++lineNumber;

现场示例