[英]first char is not stored in a string object using getline() function of string header in c++
string nums;
int main() {
int cases;
scanf("%d", &cases);
while (cases--) {
cin.ignore();
getline(cin, nums);
cout << nums << endl;
}
}
input example 输入范例
3
1 2 1 2 1
2 3 4 1 2 5 10 50 3 50
3 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1
I expect right result below 我希望下面有正确的结果
1 2 1 2 1
2 3 4 1 2 5 10 50 3 50
3 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1
However, the output is that 但是,输出是
1 2 1 2 1
3 4 1 2 5 10 50 3 50
5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1
I don't know what the reason is. 我不知道是什么原因。 I clearly use cin.ignore()
to flush the buffer. 我显然使用cin.ignore()
刷新缓冲区。 Why is the first char removed ? 为什么第一个字符被删除?
Just put the line cin.ignore();
只需将行cin.ignore();
outside the while
loop: 在while
循环之外:
Following is corrected code. 以下是更正的代码。 See it working here : 看到它在这里工作:
string nums;
int main()
{
int cases;
scanf("%d", &cases);//Better if you use `cin>>cases;` here, just for sake of C++.
cin.ignore();
while (cases--)
{
getline(cin, nums);
cout << nums <<endl;
}
return 0;
}
You should initialize your cases
to 0 just in case a user enters an invalid input for an integer type like a character or something. 如果用户为诸如字符之类的整数类型输入了无效的输入,则应将cases
初始化为0。 You should prefer to use std::cin
for user input in C++ like I stated in the comments section. 如我在注释部分所述,您应该更喜欢使用std::cin
在C ++中进行用户输入。 You can skip the \\n
newline character after your initial input by calling get()
. 您可以在初始输入后通过调用get()
跳过\\n
换行符。 It's serving the same purpose as you were trying to achieve with ignore()
. 它的作用与您尝试使用ignore()
实现的目的相同。 while(cases--)
is a bit weird to look at but I get what you're going for. while(cases--)
看起来有点怪异,但我明白了您要做什么。 You can declare your string nums
inside the loop since you're overwriting it every iteration anyway. 您可以在循环内声明string nums
,因为无论如何每次迭代都会覆盖它。 The reason you do not need to use std::cin.ignore()
in this code is because std::getline
reads everything including the newline character from console input. 您无需在此代码中使用std::cin.ignore()
的原因是因为std::getline
从控制台输入中读取了包括换行符在内的所有内容。 This code should do exactly what you want. 该代码应完全满足您的要求。
#include <iostream>
#include <string>
int main()
{
int cases(0); ///< initialize in case user enters text
(std::cin >> cases).get(); ///< use std::cin in C++; get() to skip `\n`
while (cases--) ///< is that really what you want?
{
std::string nums; ///< nums only needed locally
std::getline(std::cin, nums); ///< reads whole line + '\n'
std::cout << nums << std::endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.