Reputation: 19
can anyone tell me why gets(abc) works with char[] but not with int?
int abc;
char name[] = "lolrofl";
printf("Hello %s.\n",name);
printf("\n >> ");
fflush(stdin);
gets (abc);
printf("\n die zahl ist %i.\n",abc);
system("Pause");
return(0);
Upvotes: 1
Views: 569
Reputation: 57718
First, the gets
function is for reading strings or text, not numbers.
Second, don't use gets
as it has buffer overrun errors. See C Language FAQ for more information. The function fgets
is a safer alternative.
Third, you may want to switch to C++ streams and std::string
. The C++ streams are more type friendly than C streams.
Fourth, fflush
does not function on input streams. The fflush
function is for writing the remaining data in stream buffers to the output stream. In C++, there is a method, ignore
, which will ignore incoming characters until a newline (default) or a specified character is read (or a limit is reached).
Hope that helps.
Upvotes: 0
Reputation: 95539
The prototype for gets() is:
char* gets(char *s);
Note that the function DOES NOT read just a single character and place it in s; it actually reads an entire string into s. However, since gets() does not provide a way of specifying the maximum number of characters to read, this can actually read more characters into s than there are bytes allocated for s. Thus, this function is a serious buffer overflow vulnerability, and you should not use this function, ever. There are alternative, safer functions which allow you to read input from the user such as fgets() and getc().
If you are using C++, then using the C++ I/O Stream Library (std::cin, std::cout, std::ostream, std::istream, std::fstream, etc.) is a far better way to perform input/output than using these other functions.
The function gets() is so dangerous, in fact, that in my development and coding custom search engine, I have taken out a promotion on gets and several other such functions warning not to use it!
Upvotes: 11
Reputation: 829
If you take a look at the C Reference your question will be answered. I'll paste it for you:
char *gets( char *str );
The gets() function reads characters from stdin and loads them into str, until a newline or EOF is reached. The newline character is translated into a null termination. The return value of gets() is the read-in string, or NULL if there is an error. Note that gets() does not perform bounds checking, and thus risks overrunning str. For a similar (and safer) function that includes bounds checking, see fgets().
So you won't be able to cast a whole string to an integer.
Upvotes: 1
Reputation: 36946
Because it only reads characters. Use scanf() for formatted reading.
By the way, since you appear to be using C++ (or at least your choice of tags says so), perhaps you should try std::cin/std::cout.
Upvotes: 4