What is the C equivalent to the C++ cin
statement? Also may I see the syntax on it?
views:
228answers:
4You probably want scanf
.
An example from the link:
int i, n; float x; char name[50];
n = scanf("%d%f%s", &i, &x, name);
Note however (as mentioned in comments) that scanf is prone to buffer overrun, and there are plenty of other input functions you could use (see stdio.h
).
In c++, cin is the stdin input stream. There is no input stream in C, but there is a file object, called stdin. You can read from it using a lot of ways, but here's an example from cplusplus.com:
/* fgets example */
#include <stdio.h>
int main()
{
char buffer[256];
printf ("Insert your full address: ");
if (fgets(buffer, 256, stdin) != NULL) {
printf ("Your address is: %s\n", buffer);
}
else {
printf ("Error reading from stdin!\n");
}
return 0;
}
UPDATE
I've changed it to use fgets, which is much simpler since you have to worry about how large your buffer is. If you also want to parse the input use scanf, but make sure that you use the width attribute.
There is no close equivalent to cin
in C. C++ is an object oriented language and cin
uses many of its features (object-orientation, templates, operator overloading) which are not available on C.
However, you can read things in C using the C standard library, you can look at the relevant part here (cstdio reference).
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.