Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

c - not able to read string after reading double data type

I am trying a c program with following input.

6
7.0
How are you

I am able to read and print the integer and double datatype variable but string variable is not accepting any input from user and printing the integer variable value by itself

Code for int:

int j;
double e;
char str[100];

printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("enter the string :");
scanf("%[^
]s",str);
printf("integer variable is %d
",j);
printf("float variable is %0.1f
",e);
printf("string variable is %s
", str);

Output:

enter the integer :3
enter the double :4.0
enter the string :integer variable is 3 -> (automatically accepting printf of integer case and exiting the code)
float variable is 4.0
string variable is ??LX?

But If I am reading string value first (before reading integer and double) then code is working fine.

Code for string:

printf("enter the string :");
scanf("%[^
]s",str);
printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("integer variable id %d
",j);
printf("float variable is %0.1f
",e);
printf("string variable is %s
", str);

Output:

enter the string :how are you
enter the integer :6
enter the double :7.0
integer variable is 3
float variable is 4.0
string variable is how are you
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a space before the conversion format in scanf():

scanf(" %99[^
]", str);  // skip whitespace and read up to 99 characters on a line

This will instruct scanf() to skip the pending newline sitting in the stdin buffer, as well as any leading spaces in the next line. As a matter of fact, it will keep reading lines until the user types a non empty one or the end of file is reached. You should test the return value of scanf() to verify if scanf() succeeded.

Furthermore, you must tell scanf() the maximum number of characters to store into str otherwise a sufficiently long line of input will cause a buffer overflow with dire consequences, as this may constitute an exploitable flaw.

Note also that the syntax for parsing a scanset is %99[^ ]: no trailing s is required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...