Scanf ("% s") keeps the string even after using it after scanf ("% d")
So, I wrote this code (ignore the buffer overflow issue as this is just a simple example):
#include<stdio.h>
int main(void){
int n;
char s[10];
printf("Enter a number: ");
scanf("%d",&n);
scanf("%s",s);
printf("%s",s);
return 0;
}
The string should not be stored in an array because there must be "\ n" in the input buffer and therefore scanf ("% s", s) must be terminated, but it is not. The output prints out a string.
source to share
The format specifier %s
skips leading spaces, i.e. all '\n'
, ' '
, '\t'
, ... they will be ignored, and s[0]
will contain the first non input.
To demonstrate a little what is happening in scanf
, see the following example, which uses "%n"
-feature scanf
, which returns the number of characters that have been processed so far; And I used sscanf
to make the result independent of user input. Note that when reading, the string scanf
processes more characters than is stored in the result:
#include<stdio.h>
int main(void){
int n;
int pos;
char s[10];
const char* simulatedInput = "123\n abcde";
const char* inputPtr = simulatedInput;
sscanf(inputPtr,"%d%n",&n,&pos);
printf("sscanf on %s processed %d charaters; result n: %d\n", inputPtr, pos, n);
inputPtr += pos; // inputPtr will point at the position of '\n'
sscanf(inputPtr,"%s%n",s,&pos);
printf("sscanf on %s processed %d charaters; yet s as '%s' contains only %lu characters\n", inputPtr, pos, s, strlen(s));
return 0;
}
Output:
sscanf on 123
abcde processed 3 charaters; result n: 123
sscanf on
abcde processed 11 charaters; yet s as 'abcde' contains only 5 characters
source to share