tags:

views:

4475

answers:

5

Hi, I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using cin.get( input, '\0' ) but '\0' is not really the EOF character, that just reads until EOF or '\0', whichever comes first.

Or is using loops the only way to do it? If so, what is the best way?

Thanks in advance.

A: 

You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.

luke
+8  A: 

The only way you can read a variable amount of data from stdin is using loops. I've always found that the std::getline() function works very well:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

By default getline() reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to getline().

trotterdylan
+2  A: 

This was answered nicely here.

Ferruccio
That's a different question with different requirements.
Konrad Rudolph
That's an excellent thread, but addresses file i/o and rather than input from the command line.
luke
Right. But if you use cin in place of the ifstream, that should give him what he wants: to read everything till the EOF in one gulp.
Ferruccio
Does fseek() work on stdin?
Martin York
fseek() won't, but seek() will.
KeithB
the seek() will not work on console input, but the stream iterators will. I think it's the best solution, and I am very grateful to the author for teaching me something.
Arkadiy
+3  A: 

You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.

#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>

int main()
{
// don't skip the whitespace while reading
  std::cin >> std::noskipws;

// use stream iterators to copy the stream to a string
  std::istream_iterator<char> it(std::cin);
  std::istream_iterator<char> end;
  std::string results(it, end);

  std::cout << results;
}
KeithB
Nice. As for "I'm sure that it uses some kind of loop internally" - any solution would.
Michael Burr
+1  A: 

Using loops:

#include <iostream>
using namespace std;
...
// numbers
int n;
while (cin >> n)
{
   ...
}
// lines
string line;
while (getline(cin, line))
{
   ...
}
// characters
char c;
while (cin.get(c))
{
   ...
}

resource

Delynx