Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

What is the C equivalent to the C++ cin statement? Also may I see the syntax on it?

like image 209
rectangletangle Avatar asked Sep 16 '10 03:09

rectangletangle


People also ask

Does C have cout and cin?

cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.

What is the syntax of CIN in C++?

The syntax of the cin object is: cin >> var_name; Here, >> is the extraction operator.

Which operator is used with CIN in C++?

Standard input stream (cin) It is connected with the standard input device, which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the input from a console. Let's see the simple example of standard input stream (cin): #include <iostream>

What data type is Cin?

cin is an object of istream class type.


2 Answers

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.

like image 77
paxdiablo Avatar answered Sep 30 '22 11:09

paxdiablo


You 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).

like image 34
sje397 Avatar answered Sep 30 '22 12:09

sje397