What is the C equivalent to the C++ cin statement?

cin is not a statement, it’s a variable that refers to the standard input stream. So the closest match in C is actually stdin.

If you have a C++ statement like:

std::string strvar;
std::cin >> strvar;

a similar thing in C would be the use of any of a wide variety of input functions:

char strvar[100];
fgets (strvar, 100, stdin);

See an earlier answer I gave to a question today on one way to do line input and parsing safely. It’s basically inputting a line with fgets (taking advantage of its buffer overflow protection) and then using sscanf to safely scan the line.

Things like gets() and certain variations of scanf() (like unbounded strings) should be avoided like the plague since they’re easily susceptible to buffer over-runs. They’re fine for playing around with but the sooner you learn to avoid them, the more robust your code will be.

Leave a Comment