[英]why extra blank line is printed while printing B?
這是從文本文件中獲取輸入的代碼。 我使用了charecter明智的閱讀。 當我打印B時,它僅在'rao'之后打印額外的行。
我的文本文件輸入是:
1 singh
2 sen singh rao singh pal sen jain sen de rao
3
這是代碼
int main() {
ifstream in;
in.open( "Text.txt" );
string s;
while(getline(in,s)){
char x;
x=in.get();
if(x=='1'){
string s;
in>>s;
}
if (x=='2'){
char c;
c=in.get();
c=in.get();
do{
string A;
string B;
do{
A=A+c;
c=in.get();
} while(c!=' ');
c=in.get();
do{
B=B+c;
c=in.get();
} while(c!=' '&&c!='1'&&c!='2'&&c!='3'&&c!='4'&&c!='5'&&c!='6'&&c!='7');
cout<<B<<endl;
}
while(c!='1'&&c!='2'&&c!='3'&&c!='4'&&c!='5'&&c!='6'&&c!='7');
if(c!='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'){
in.putback(c);
}
}
}
}
std::endl
插入換行符並刷新流。 如果你只想刷新使用std::flush
但說實話,大多數時候你都不需要。
首先,您可能需要修改代碼,就像忘記輸入文件中行尾的空白區域一樣,在此處進入無限循環:
do{
A=A+c;
c=in.get();
} while(c!=' ');
如果該行中的最后一個字符是' '
沒關系:你退出這個循環,但是c=in.get();
在您將char換行符加載到c之后。
字符串B上的while循環首先將c(這是一個換行符char)加載到空字符串B中。然后從文件中讀取char 3,這樣就可以退出循環。
現在很明顯, cout
打印了兩個新行:一個在B中,另一個來自endl
。
如果您認為輸入文件是這樣的話,可能會更清楚:
1 singh[newline]2 sen singh rao singh pal sen jain sen de rao [newline]3
一個快速的解決方案是把這條線放在cout之前:
if (B=="\n") B.clear();
我不確定代碼的目標,所以我很難提出更好的設計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.