user1989216
user1989216

Reputation:

Read from input in a declaration in C++?

So I'm coming from Java where you can do something like this when using a Scanner

int n = s.nextInt();

Now that I'm dabbling with C++, I find it annoying to do:

int n;
cin >> n;

Is there a shorthand way to read from input in a variable declaration?

Upvotes: 0

Views: 119

Answers (3)

Robin Hartland
Robin Hartland

Reputation: 336

Making the functions suggested by dasblinkenlight and Michael Aaron Safyan more generic using templates (now incorporated into final example of Michael's answer):

#include <iostream>

template<typename T> T read();

template<typename T>
T read<T>() {
    T ret;
    std::cin >> ret;
    return ret;
}

int main() {
    int i = read<int>();
    double d = read<double>();
    std::cout << i << std::endl << d;
    return 0;
}

Upvotes: 3

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95569

You can just make a helper function to do this for you:

// Using an anonymous namespace, since this is intended to
// be just an internal utility for your file... it's not
// a super awesome, shareable API (especially since it hard
// codes the use of std::cin and has no error checking).
namespace {

// Helper function that reads an integer from std::cin.
// As pointed out in Robin's solution, you can use a template
// to handle other types of input, as well.
int ReadInt() {
  int result;
  std::cin >> result;
  return result;
}
}

Then you can do:

int n = ReadInt();

If you want to really go all out, though, you can create a more elaborate solution:

namespace input_utils {
class IOException {};
class Scanner {
  public:
     Scanner() : input_(std::cin) {}
     Scanner(std::istream& input) : input_(input) {}

     template<typename T> T Read() {
       CheckStreamOkay();
       T result;
       input_ >> result;
       CheckStreamOkay();
       return result;
     }

  private:
     void CheckStreamOkay() {
       if (!input_) {
         throw IOException();
       }
     }
     std::istream& input_;
};
}

Then you can do something like:

input_utils::Scanner scanner(std::cin);
int a = scanner.Read<int>();
int b = scanner.Read<int>();
double c = scanner.Read<double>();
...

Though, at that point, you might want to look for an existing library that already does this.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

There is no built-in shortcut for this, but you could certainly make your own function for this:

int read_int() {
    int res;
    cin >> res;
    return res;
}
...
int a = read_int();

Upvotes: 3

Related Questions