3

For example...

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

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

Evan Carslake
  • 2,267
  • 15
  • 38
  • 56

3 Answers3

3

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
2

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++.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • Yes and printf also can be used in C++...but nobody uses it. I'm just asking if there's another way to do this --'...without using c libraries. – Felipe Endlich Jun 20 '15 at 01:05
  • You are probably going to end up [even if you don't do it yourself] include some "c" libraries whatever you do. – Mats Petersson Jun 20 '15 at 01:19
0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Dian Sheng
  • 47
  • 2