程序必须读取一个整数列表,并按下Enter to 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
如何改进此代码以便读取和打印第一个整数。
提前致谢:)
答案 0 :(得分:2)
cin.get()
从标准输入中读取一个字符并将其返回。您不会将cin.get()
的返回值分配给变量。因此,刚刚读取的值将丢失。
答案 1 :(得分:1)
除了忽略get()的结果外,你的代码将会结束 在无限循环中,如果输入包含无效字符 (如果cin&gt;&gt; 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;
}
答案 2 :(得分:1)
您可以阅读整行,然后解析它。其中一个变体(对代码进行了最少的修改)如下:
#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 4\n5 6 7 8\n"|./main
1 2 3 4
5 6 7 8