This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 28 days ago.
I am getting problem when using scanf() to take int input, then move to take a whole string that also accept whitespace in it. But somehow the scanf() take place first before the printf() even showed up. Still playing around with either scanf() and fgets() for proper solutions
Here is my snippet code
int age; char name_user[35];
printf("age\t: "); scanf("%d\n",&age);
printf("name\t: "); scanf("%[^\n]%*s", name_user);
printf("result\t: %s is %d years old\n",name_user,age);
with the output like this
age : 30
hotpotcookie
name : loremipsum
result : hotpotcookie is 30 years old
are there any workarounds for the input hotpotcookie take place in the name output? so it could be similar like this
age : 30
name : hotpotcookie
result : hotpotcookie is 30 years old
"\n" consumes 0 or more white-spaces until a non-white-space is detected. This means scanf() will not return at the end-of-line as it is looking for white-spaces after a '\n'.
scanf("%d\n",&age); does not return until detecting non-white-space after the numeric input.
Use scanf("%d",&age);.
scanf("%[^\n]%*s", name_user); also risks buffer overflow.
Use a width as in scanf(" %34[^\n]", name_user);
Better code checks the return value from scanf() before using the object(s) hopefully populated by the scan.
Even better code does not use scanf(). Instead use fgets() to read a line of user input into a string and then parse with strotl(), sscanf(), etc.
Related
This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 4 years ago.
I mistakenly used scanf("%d\n",&val); in one of my programmes, I could not understand the behavior, the function showed.
int main(){
int val;
scanf("%d\n", &val);
printf("%d\n", val);
return 0;
}
Now the program required 2 integer inputs, and prints the first input that was entered.
What difference should that extra \n brings?
I tried to search but couldn't find the answer, even through manual of scanf.
An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input. So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream (e.g. when the input is redirected from a file and its end is reached, or after you closed stdin with Ctrl-D).
From man scanf in my Linux box:
A directive is one of the following:
A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
BTW, %d is also a directive.
So your "%d\n" has two directives, the first one reads the number and the second one... well reads any amount of white space, including your end-of-lines. You have to type any non-white space character to make it stop.
This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 6 years ago.
#include <stdio.h>
int main() {
float change = 0.0;
printf("O hai! ");
while (change <= 0) {
printf("How much change is owed?\n");
scanf("%f\n", &change);
}
return 0;
}
and the result if input is a negative is endless "How much change is owed?"
scanf is actually entered, but due to the \n in format string "%f\n", after having entered a number, scanf waits for the next non-whitespace character to return. Note that a white space in format specifier lets scanf consume a sequence of any white space characters, not only one, and so it "hangs" as long as only white space characters are provided by the stream.
Change scanf("%f\n",&change) into scanf("%f",&change).
When you ask a computer to discard whitespace, how does it know what it's done? Answer: As soon as it reads something that's not whitespace.
You asked it to discard whitespace after reading a number. Thus it's not done until it reads the number and then reads some non-whitespace.
That really doesn't make any sense since there's no reason anyone would enter non-whitespace after entering the number.
Here's a tip though that will save you pain in the future: If what you really want to do is read a line of input then parse it, use a function that reads a line and then some code to parse that input.
This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 6 years ago.
I just had a test in my C class today and I have reason to believe that answer might be incorrect.
scanf("%d\n", &x); // Evaluate the expression for the string "54321\n"
The idea is pretty simplistic. Find an integer and place the scanned number at the memory location corresponding with integer variable x. However, I don't believe that this call to scanf would ever terminate.
As far as I am concerned, all calls to scanf to standard I/O terminate with the press of the enter key, so there is no need to include the newline in the specifier string. In fact, this redundancy will only cause the program to stall in search of something that will never match the string.
Is there anyone who can clarify the technicalities of the scanf function to put this problem to rest?
I don't believe that this call to scanf would ever terminate.
6 character input like "54321\n" is insufficient to cause this scanf("%d\n", &x); to return. The program stalls. Something else must yet occur.
'\n' directs scanf() to consume white-spaces and to do so until
a non-white-space is detected.
stdin is closed
An input error occurs on stdin (rare).
As stdin is usually line buffered, scanf() receives data in chunks.
The first chunk 123Enter is not enough to cause scanf("%d\n", &x); to return. One of the 3 above needs to happen.
Any following input with some non-white-space fulfills #1, be it:
456Enter or
xyzEnter or
EnterEnter$Enter or ...
Then scanf() will return with a 1 indicate a value, 123, was stored in x. The 4, x or $ above was the non-white-space detected that caused completion. That character will be the next character read by subsequent input on stdin.
scanf("%d\n", &x); is almost certainly the wrong code to use as it obliges another line of user input and does not check its return value.
all calls to scanf to standard I/O terminate with the press of the enter key, so there is no need to include the newline in the specifier string.
That's correct. The \n in the format string will ignore any number of whitespaces, including the "ENTER" key; so, you'll have to input a non-whitespace char to terminate the scanf() call. So, yes, the \n is problematic.
scanf()'s man page says:
ยท A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.
By the way, scanf() itself is considered problematic: Why does everyone say not to use scanf? What should I use instead?
This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
I need to get words from user which contains space as I expressed at title with struct statement.
For example :
#include <stdio.h>
struct knowledge
{
char name[30];
}person;
int main()
{
scanf("%s",person.name);
printf("\n\n%s",person.name);
}
When I run this program and enter a sentence like "sentence" there is no problem. It show me again "sentence".
However, when I enter "sentence aaa" it shows me just first word ("sentence"). What is the matter here? Why it doesn't show me all ("sentence aaa") I entered?
Instead of scanf() use
fgets(person.name,sizeof(person.name),stdin);
It is always a bad idea to use scanf() to read strings. The best option is to use fgets() using which you avoid buffer overflows.
PS: fgets() comes with a newline character
%s format specifier stops scanning on encountering either whitespace or end of stream. hence, you cannot input a "sentence" with space using scanf() and %s.
To scan a "whole line" with space, you need to use fgets(), instead.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you allow spaces to be entered using scanf?
printf("please key in book title\n");
scanf("%s",bookname);
i inside the data like this :-
C Programming
but why output the data like this :-
C
lose the Programming (strings) ?
why
thanks.
The %s conversion specifier causes scanf to stop at the first whitespace character. If you need to be able to read whitespace characters, you will either need to use the %[ conversion specifier, such as
scanf("%[^\n]", bookname);
which will read everything up to the next newline character and store it to bookname, although to be safe you should specify the maximum length of bookname in the conversion specifier; e.g. if bookname has room for 30 characters counting the null terminator, you should write
scanf("%29[^\n]", bookname);
Otherwise, you could use fgets():
fgets(bookname, sizeof bookname, stdin);
I prefer the fgets() solution, personally.
Use fgets() instead of scanf()
Well bookname surly is some kind of char ;-)
Point is that scanf in this form stop on the first whitespace character.
You can use a different format string, but in this case, one probably should prefer using fgets.
scanf really should be used for "formatted" input.