+ 1

I'm getting an error in a C code.

#include <stdio.h> int main () { int n; char str[50]; printf("Enter n="); scanf("%d",&n); //Whenever I use these two statements I get a warning as "The gets() function is dangerous and should not be used" and I can't even input the string which I can if those two statements aren't there. printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); }

25th Apr 2018, 4:16 PM
Cyan
Cyan - avatar
6 Respostas
+ 4
If instead you wish to enter the data on two lines, use scanf("%d\n",&n); to force scanf to process over the new line. However, entering: 5t test Will get the t, not test as it only skips the newline immediately after the number.
25th Apr 2018, 5:48 PM
John Wells
John Wells - avatar
+ 2
I don't know about your error as I didn't recieve one. But, it is right as gets reads until end of line so can overwrite your string clobbering other variables. You should enter your data like: 5test. scanf stops once it sees the t setting n to 5. gets reads the rest of the line into str.
25th Apr 2018, 5:41 PM
John Wells
John Wells - avatar
+ 2
That is a function of how SoloLearn playground works. The program is run remotely on a server so before it starts the app prompts for all of your input. That input is sent to the server and your program runs. Once it is complete, the output is sent back to the app for display.
25th Apr 2018, 6:09 PM
John Wells
John Wells - avatar
+ 2
I've never used CodeBlocks so I can't tell you. If you use an actual compiler on a local system, your prompts will get displayed prior to your input being read.
25th Apr 2018, 6:20 PM
John Wells
John Wells - avatar
+ 1
John Wells I've one more problem even if I've given printf( ) earlier than gets( ) it's appearing after the string has been entered.
25th Apr 2018, 6:05 PM
Cyan
Cyan - avatar
+ 1
John Wells I've tried it on CodeBlocks too. It's the same. CodeBlocks is the standard I guess.
25th Apr 2018, 6:17 PM
Cyan
Cyan - avatar