getline()一个字符串给出困难 [英] getline() a string giving difficulty
问题描述
我在做一个任务,我输入的时间,你想输入,然后我输入一个完整的行使用getline,但sime我不能这样做。
这里,当我尝试输入'1'作为我的no。的测试用例,它立即给出'0'作为答案和循环,为什么不是这个cin >> test;这里与getline(cin,s)兼容;
#include< iostream>
#include< string>
using namespace std;
int main()
{
int test,j;
cin>> test;
int len;
string s;
for(j = 1; j <= test; j ++)
{
getline(cin,s);
len = s.length()
cout<< len;
}
return 0;
}
难度
输入:
1
输出:
0
预期
输入:
1
Hello World
output
11
get my answer
#include< iostream>
#include< string>
#include< cstdio>
using namespace std;
int main()
{
int test,j;
scanf(%d\\\
,& test);
int len;
string s;
for(j = 1; j <= test; j ++)
{
getline(cin,s);
len = s.length();
cout<< len;
}
返回0;
}
operator>>
在输入缓冲区中提取的数字后面留下尾随换行符,但是对于使用 operator>>
的后续读取不会出现问题,因为它会在读取之前跳过它找到的所有空格。另一方面, getline
读取直到找到分隔符(默认情况下为 \\\
),而不跳过任何内容。 / p>
长故事:如果你想使用 getline
,你必须从 c>:
#include< limits>
// ...
cin>> test;
cin.ignore(numeric_limits< streamsize> :: max(),'\\\
');
i am doing a task where i am inputting ist no of times you want to have input and then i am inputting a full line by the use of getline but sime how i am not able to do that.
here when i try to input '1' as my no. of test cases it instantly gives '0' as answer and out of the loop why is not this cin>> test; here compatible with getline (cin,s);
#include<iostream>
#include<string>
using namespace std;
int main()
{
int test,j;
cin>>test;
int len;
string s;
for(j=1;j<=test;j++)
{
getline( cin,s);
len = s.length();
cout<<len;
}
return 0;
}
the difficulty
input :
1
output:
0
expected
input:
1
Hello World
output
11
Well I mixed a little C to get My answer
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
int test,j;
scanf("%d\n",&test);
int len;
string s;
for(j=1;j<=test;j++)
{
getline( cin,s);
len = s.length();
cout<<len;
}
return 0;
}
You are mixing formatted input and unformatted input functions.
operator>>
leaves the trailing newline after the number you extracted in the input buffer, but this isn't a problem for subsequent reads done with operator>>
because it skips all the whitespace it finds before reading. On the other hand, getline
reads until it finds the delimiter (\n
by default) without skipping anything.
Long story short: if you want to use getline
you have to clean the buffer from the \n
after your cin>>test;
:
#include <limits>
// ...
cin>>test;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
这篇关于getline()一个字符串给出困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!