读取整数并在按新行时打印,直到C++文件末尾
reading integers and printing on pressing new line untill end of file in C++
程序必须读取整数列表并按回车键打印它们直到endoffile(或ctrl + C)
前任:
1 2 3 4
1 2 3 4
3 1 2 4
3 1 2 4
while(cin.get()!=-1){
i=0;
while(1) {
if(cin.get()=='n') {
break;
}
else {
cin >> a[i];
i++;
}
}
for(k=0;k<i;k++) {
cout << a[k]<< " ";
}
}
但它没有给出第一个整数,原始输出如下
前任:
1 2 3 4
2 3 4
3 1 2 4
1 2 4
如何改进此代码以便读取和打印第一个整数。
提前致谢:)
cin.get()
从标准输入中读取一个字符并返回它。不要将 cin.get()
的返回值分配给变量。因此,刚刚读取的值将丢失。
除了忽略 get() 的结果,你的代码将结束在无限循环中,如果输入包含无效字符(如果 CIN>> a[i] 失败)。
#include <cctype>
#include <iostream>
#include <sstream>
int main()
{
std::cout << "Numbers: ";
{
std::string line;
if(std::getline(std::cin, line)) {
std::istringstream s(line);
int number;
while(s >> number) {
std::cout << number << ' ';
};
// Consume trailing whitespaces:
s >> std::ws;
if( ! s.eof()) { std::cerr << "Invalid Input"; }
std::cout << std::endl;
}
}
std::cout << "Digits: ";
{
std::istream::int_type ch;;
while((ch = std::cin.get()) != std::istream::traits_type::eof()) {
if(isdigit(ch)) std::cout << std::istream::char_type(ch) << ' ';
else if(isspace(ch)) {
if(ch == 'n')
break;
}
else {
std::cerr << "Invalid Input";
break;
}
};
std::cout << std::endl;
}
return 0;
}
您可以读取整行,然后对其进行解析。其中一个变体(对代码进行最少的修改)如下:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
int i, k;
char a[1024] = {0};
string str;
while(cin.good()){
i=0;
getline(cin, str);
stringstream ss(str);
while (ss >> a[i]) { if (++i > 1024) break; }
for(k=0;k<i;k++) {
cout << a[k] << " ";
}
cout << endl;
}
}
输出:
g++ -o main main.cpp ; echo -ne " 1 2 3 4n5 6 7 8n"|./main
1 2 3 4
5 6 7 8
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 如何从文本文件中读取数值,直到遇到字符类型?
- C++运行直到按键
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 当 getline 直到新行才读取时会发生什么?
- 如何反复调用函数直到满足模拟?
- 如何打印下一个字母直到 Z 并继续到 A?
- 为什么即使直到最后才定义实际类型,也可以将依赖名称视为完整
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 打印质数直到 N 以 C++
- 读取二进制文件直到结束 c++
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?
- 擦除矢量中的所有元素,直到第一个非零元素C++
- 延迟函数使打开的框架窗口冻结,直到指定的时间过去
- 继续运行程序而无需任何干预,直到要求退出为止
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- C++-打印素数直到N
- 如何等待密钥事件,直到进程在 QT 中完成