为什么此代码从标准输入中少一个输入?
why this code takes one less input from standard input?
给出输入为:
输入: 3 1 2 3 4 5 6 7 8 9 10 11 12 预期输出: 1 2 3 4 5 6 7 8 9 10 11 12 但它给出了输出-
1 2 3 4 5 6 7 为什么不给出最后一行?我的代码中是否有任何错误?
#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{ string str;
getline(cin,str,'n');
cout<<str<<endl;
}
return 0;
}
这是因为cin>>t
不读取行尾。第一次调用getline
时,您得到一个空字符串。
我可以随手想到几种解决这个问题的方法。首先是跳过第一个数字末尾的空格,因为换行符算作空格。不幸的是,这也将跳过下一行开头的空格。
cin >> t >> std::ws;
另一种方法是使用getline
跳过行尾并忽略您返回的字符串。
cin >> t;
getline(cin, str, 'n');
相关文章:
- 有没有办法在使用 GLFW 按下按键后只处理一个输入事件?
- 为什么在我的程序中输入另一个输入会给我不同的结果
- 当被一个输入分开时,有两个控制台输出同时显示
- 为什么此代码从标准输入中少一个输入?
- GoogleMock:如何根据另一个输入参数设置ArgReferee?
- 我的代码仅适用于一个输入.请指教
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- "cin.get"停止了另一个输入函数,如"cin"..C++
- 使用getline()将字符串输入到程序中会导致下一个输入出现某种溢出
- 当我使用 cin 进行两个输入时,如何接受一个输入
- 如何从文件中一次读取一个输入,类似于在c++中使用cin/scanf从控制台读取输入
- 检查两个字符串是否相等,一个输入与另一个来自文件的输入相等
- STD :: Stringstream一次仅支持一个输入
- 如何在另一个输入语句中使用变量
- 一个输入多个输出文件C
- C 仅允许一个输入
- 整数输入 拒绝非整数输入并在C++中请求另一个输入
- 正在擦除文件中的最后一个输入
- 有没有一种方法可以测试一个输入是否是C++中的数字
- 你能定制一个输入的换行符(C++)吗