使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
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;
}
}
输入示例
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
我希望在
下方正确的结果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
但是,输出是
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
我不知道原因是什么。我显然使用cin.ignore()
冲洗缓冲区。为什么要删除第一个字符?
只需将行cin.ignore();
放在while
循环外:
以下是更正的代码。在这里看到它:
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;
}
您应该初始化 cases
至0,以防用户输入无效的整数输入,例如字符或其他东西。您应该更喜欢将std::cin
用于C 中的用户输入,就像我在评论部分中所述。您可以通过调用get()
在初始输入后跳过n
Newline字符。它的目的与您尝试实现ignore()
相同的目的。while(cases--)
看来有些奇怪,但我明白了您的目标。您可以在循环内声明您的string nums
,因为您无论如何都会覆盖它。您不需要在此代码中使用std::cin.ignore()
的原因是因为std::getline
读取所有内容,包括控制台输入中的newline字符。此代码应该完全做您想要的。
#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;
}
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- 在将字符串转换为整数后,是否有一种方法可以保持数字的第一个零
- 将第一个boost::regex匹配放入字符串中
- 有一个字符串如何从第一个' /r/n/r/n '得到它的内容,直到2行从字符串结束
- 删除二进制字符串中的第一个0