问题
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;
}
Is there such a way or no?
回答1:
The pattern that I like is:
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
}
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.
To save into a vector:
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);
}
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;
回答2:
The simplest way is to do it like this (similar was suggested but the .fail() and .eof() functions of std::istream shouldn't usually be used like that):
int main (int argc, char* argv[])
{
std::string line;
while (std::getline (std::cin, line))
{
std::cout << line << std::endl; // std::getline skips the newline
}
std::cout << "No more lines" << std::endl;
return 0;
};
回答3:
You can add an ending condition like 0 if you are reading from console. If user enters 0 it will end taking input.
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
while(n!=0) {
cout << //current line//
//increment to next line//
cin>>n;
}
return 0;
}
回答4:
How about std::cin >> std::cout.rdbuf();
? It will end when you enter EOF via CTRL-Z or likewise. Here's a sample:
#include <iostream>
int main() {
std::cin >> std::cout.rdbuf();
}
Input:
1
5
4
2
(EOF)
Output:
1
5
4
2
Saving them into an array and printing them later works just as well:
std::vector<int> inputs(std::istream_iterator<int>(std::cin), std::istream_iterator<int>());
std::copy(std::begin(inputs), std::end(inputs), std::ostream_iterator<int>(std::cout, "\n"));
来源:https://stackoverflow.com/questions/12875650/multi-line-stdin-c