多行标准输入-C ++ [英] Multi-line stdin - C++
本文介绍了多行标准输入-C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,如果我有一个采用stdin之类的程序,例如
So if i have a program that takes stdin such as
1
5
2
4
我该如何精确地说出每一行并打印出该值,这就是我的想法:
How exactly can i go through each line and say print that value, This is what im thinking:
#include <iostream>
using namespace std;
int main()
{
while ( // input has ended// ) {
cout << //current line//
//increment to next line//
}
return 0;
}
有没有办法?
推荐答案
我喜欢的模式是:
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
}
与其他答案一样,您可以键入 CTRL + Z
将 EOF
发送到 STDIN
.如果 STDIN
是管道,则当流中没有更多数据时,将发送 EOF
.
As in the other answers, you can type CTRL+Z
to send an EOF
to STDIN
. If STDIN
is a pipe, then EOF
will be sent when the stream has no more data.
要保存到向量中:
vector<int> numbers;
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
istringstream iss(line);
int num;
iss >> num;
numbers.push_back(num);
}
如果您想要C样式的数组(尽管我会推荐 std :: vector
:
If you want a C-style array (although I would recommend std::vector
:
size_t START_SIZE = 100;
size_t current_size = START_SIZE;
size_t current_index = 0;
int* numbers = new int[current_size];
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
if (current_index == current_size)
{
current_size += START_SIZE;
int* tmp_arr = new int[current_size];
for (size_t count = 0; count < current_index; count++)
{
tmp_arr[count] = numbers[count];
}
delete [] numbers;
numbers = tmp_arr;
}
istringstream iss(line);
int num;
iss >> num;
numbers[current_index] = num;
current_index++;
}
delete [] numbers;
这篇关于多行标准输入-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文