2016-05-15 21 views
0

所以每次我使用while循環從文件中讀取字符串時,總會有一個額外的空字符串被最後處理。 ifstream fin(「A7infile.txt」);while(getline())循環在最後一次傳遞後沒有空字符串

while(getline(fin,line)) 
{ 
    cout<<"Original Line: "<<line<<endl<<endl; 
    breakup(line,first,middle,last); 
    cout<<first<<" :is first"<<endl; 
    cout<<middle<<" :is middle"<<endl; 
    cout<<last<<" :is last\n"<<endl; 
    neww=makealpha(first,middle,last); 
    cout<<neww<<" :is the alphabetized line\n"<<endl; 
} 
fin.close(); 
return 0; 

這是我用一個空字符串

Original Line: lolipops And Rainbows 

lolipops :is first 
And :is middle 
Rainbows :is last 

And Rainbows lolipops :is the alphabetized line 

Original Line: 

:is first 
:is middle 
:is last 

:is the alphabetized line 

我如何才能在最後一傳擺脫空字符串的意思嗎?

+0

你可能有額外的換行符的地方,你可以只檢查'line.empty()'。 –

+0

文件末尾是否有空行? –

回答

0

如果你想跳過空行的文件,在年底或在中間,你可以添加一個檢查循環的身體跳過他們:

while(getline(fin,line)) { 
    if (line.empty()) { 
     continue; 
    } 
    // the rest of your code goes ehre 
} 
1

std::string::emptyreference)可用於檢查std::string是否爲空。

因此,請檢查line是否爲空,如果不是,請運行您的代碼,否則不執行任何操作。

例子:

while (getline(fin, line)) 
{ 
    if (!line.empty()) 
    { 
     // Your logic here... 
    } 
} 
相關問題