What's the C++ version of scanf?

8.9k views Asked by At

For example...

char* foo;
scanf("%[^\n\r]", foo);

How can I do this in C++, without including C libraries?

3

There are 3 answers

2
Barry On

The C++ version of scanf is std::scanf and can be found in the <cstdio> header. Yes, it's the same function - because C functions can also be used in C++.

7
Mats Petersson On

The equivalent to what you have posted [aside from the fact that char *foo without an allocation of memory, probably will lead to writing to either NULL or some random location in memory] would be

 std::string foo;
 std::getline(std::cin, foo);

But for more complex cases, where you read multiple items, either cin >> x >> y >> z; or std::getline(std::cin, str); std::stringstream ss(str); ss >> x >> y >> z; - or some combination thereof.

But C-code that is valid is valid in C++ too. It's not always the "right" solution, but certainly not completely wrong either.

0
Dian Sheng On

There are two simple methods to replace scanf.

  1. std::cin which can be found in the standard library.

  2. std::getline(std::cin, line); which takes user's input, up to but not including the line break, into a std::string variable line.