Reputation: 35
I'm trying to convert this code from C++ into C:
int num{0};
std::cin >> num;
I need an equivalent to std::cin
. I've already tried:
int num = 0;
fgets (num, 0, stdin);
What can I do?
Upvotes: 0
Views: 267
Reputation: 51825
Is there a C equivalent of C++'s std::cin
Not really. The C++ std::cin
represents a specific instance of the std::istream
class, for which the >>
(formatted input) operator has a number of overloads (at least one of which is templated). Thus, that one operator can effectively handle a variety of different input types.
The closest thing that C has is the stdin
file handle, which (generally speaking) represents the same input stream as std::cin
. However, although you can use stdin
in formatted input operations (like fscanf
), you can also use the more general scanf
function (which uses the same input stream).
However, you will need to specify the format options explicitly, for each input type (use %d
for an int
type), like so:
int num = 0;
scanf("%d", &num);
Or, for the more 'general' case:
int num = 0;
fscanf(stdin, "%d", &num);
Upvotes: 3
Reputation: 57
using scanf ("%d", &var);
scanf will put the value of the input directly into var.
it will wait until the user press Enter or any other key.
Upvotes: 0