[英]I am getting wrong output in my cpp program
while(t--){
string str, token, dummy;
cin.ignore();
getline(cin ,str);
int pos = str.find(' ');
token = str.substr(pos+1);
str = str.substr(0, 3);
cout << str << " " << token << endl;
}
On giving input as:在提供输入时:
add hackerrank添加黑客等级
add hacker添加黑客
find hac找到hac
find hak找哈克
output comming as: output 作为:
add hackerrank添加黑客等级
dd hacker dd黑客
ind hac工业
ind hak工业
I'm missing first char of my input from second line.我缺少第二行输入的第一个字符。
From istream ignore() [emphasis added]来自 istream ignore() [强调添加]
basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );
basic_istream& 忽略(std::streamsize count = 1, int_type delim = Traits::eof());
Extracts and discards characters from the input stream until and including delim.
从输入 stream 中提取并丢弃字符,直到并包括 delim。
The default value of count
is 1
. count
的默认值为1
。 So, it is ignoring 1
character from input stream as you are calling it without any parameter.因此,当您在没有任何参数的情况下调用它时,它会忽略输入 stream 中的
1
字符。
You are observing this behaviour of ignoring first character of input from second line because you might have given some input value before while
loop (may be input value for t
, like this - cin >> t
) and hit the enter button which is leaving the stray \n
in input stream.您正在观察这种忽略第二行输入的第一个字符的行为,因为您可能在
while
循环之前给出了一些输入值(可能是t
的输入值,像这样 - cin >> t
)并点击正在离开的输入按钮输入 stream 中的杂散\n
。 The first execution of cin.ignore()
eating that stray \n
character from input stream and from second input string onwards it eating up the first character of your input. cin.ignore()
的第一次执行从输入\n
和从第二个输入字符串开始吃掉了输入的第一个字符。
To solve this problem, you can simply add cin.get()
just after the input value giving before entering while
loop and remove cin.ignore()
from loop body.为了解决这个问题,你可以简单地在输入值之后添加
cin.get()
,然后进入while
循环,然后从循环体中删除cin.ignore()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.