如何使用getline并提取字符串c ++的某些部分

时间:2018-11-10 19:33:01

标签: c++ string while-loop getline

所以我有一个包含内容的文本文件:

title
#comment 1
given
#comment 2
second given
#comment 3
1 2 3 4 5 6 7 8 9
#row 1
11 12 13 14 15 16 17 18 19 
#comment 4
20 21 22 23 24 25 26 27 28 29

我已经使用了这段代码:

while(getline(fin, str)){


 if(getline(fin, str, '#')){
cout << str << endl;  
}
  else{
cout << str << endl;
  }
 }

,以便从上方获取并打印出文本文件中的每一行,同时提取以注释或本例中的“#”开头的每一行。它工作正常,可以打印出所有内容,除了第一行显示“ title”。我需要将其与其他所有内容一起打印出来,但是为什么不打印呢?并且我有什么办法可以确保它与其他所有内容一起打印(显然除了注释。我还必须检查标题以确保在此示例中显示为“ title”。我如何访问字符串的第一部分?以便为其创建if语句

2 个答案:

答案 0 :(得分:0)

while(getline(fin, str)) {
  if(getline(fin, str, '#')){
    // ...

第一次调用getline时,您会得到第一行(很明显),然后再次调用getline,则读取第二行(显然也是),然后从缓冲区中替换第一行。

您不会在输出中看到第一行,因为您在打印前用第二行覆盖了它。

认为,您尝试做的事情是这样的:

while(getline(fin, str)) 
  if(str[0] == '#') 
    cout << "comment: " << str << endl;  
  else
    cout << "data: " << str << endl;

答案 1 :(得分:0)

您将函数getline作为条件调用了一段时间,然后读取了从文件到str的一行。然后,您无需再次调用它。它会覆盖第一个。这就是为什么第一行被跳过的原因。

if(getline(fin, str) && str == "title"){ // check the first line here 
    do {
        if(str[0] != '#')
            cout << str << endl; // print out if read line is not comment
    } while(getline(fin, str));
}

使用上面的代码,您可以先检查第一行,然后读取文件。