[英]How to use getline and extract certain parts of the string c++
所以我有一個包含內容的文本文件:
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語句
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;
調用函數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));
}
使用上面的代碼,您可以先檢查第一行,然后讀取文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.