Home > Enterprise >  Scanf function inside of while runs only one time?
Scanf function inside of while runs only one time?

Time:09-21

Why did my scanf function inside while runs only one time?

#include<stdio.h>
#include<stdlib.h>

int main()

{

char s[9999];

while(scanf("%[^\n]s",s)>0)

{ 
    
    int count=0, prev=0; 
    for (int i=0;i<strlen(s);i  )
{
if(s[i]==' ')
{
count=i-prev;
prev=i 1;
printf("%c", (char) (96 count));
}
else if(strlen(s)-1==i)
{
count=i-prev 1; printf("%c", (char) (96 count)); }
} 
printf(" ");
}}

my test case and output:

enter image description here

Input is considered as a string with a maximum length 1000

CodePudding user response:

Unless you understand scanf, you shouldn't use it. When you understand scanf, you will not use it. There are several problems with

while(scanf("%[^\n]s",s)>0)

scanf will read the input stream, writing characters into the variable s until it sees a newline. It will then try to match a literal s in the input stream. Clearly, the next character is not an s (it is a newline), so the s in the format string does not match. (This is not really a problem, but is certainly bizarre that you have asked scanf to match a literal s when an s is certainly not there. If you had tried to do further matches with something like "%[^\n]s%d", you might be confused as to why scanf never matches an integer. It is because scanf stops scanning as soon as the input stream does not match the format string, and the s in the format string will not match.) On the second iteration of the loop, the first character scanf sees is that newline, so it makes no conversions and returns 0. If you want to discard that newline and are okay with removing leading whitespace, you can simply use " %[\n]" as a conversion specifier. If you do not want to discard leading whitespace, you can discard the newline with " %[\n]%*c" Note that you really ought to protect against overwriting s, so you should use either:

while(scanf("            
  • Related