Search code examples
cscanfnewlinec-stringsconversion-specifier

Input of multiple char arrays isn't working


char toFind[100];
char replace[100];
int pos = 0;
printf("Enter a text: ");
scanf("%[^\n]", str);
printf("Enter a search pattern: ");
scanf("%[^\n]", toFind);
printf("Enter a substitute: ");
scanf("%[^\n]", replace);
pos = strnfnd(0, toFind);
strins(pos, replace);
printf("Der Text ist: %s", str);

This code sample let me read the value for str but skips the other two scanf. I have no idea why. What can I do to fix this?

Ps: str is a global char array


Solution

  • After this call of scanf

    scanf("%[^\n]", str);
    

    the new line character '\n' still is present in the input buffer.

    So the next call of scanf

    scanf("%[^\n]", toFind);
    

    that reads input until the new line character '\n' is encountered reads nothing.

    You should write for example

    scanf("%[^\n]%*c", str);
    

    to remove the new line character '\n' from the input buffer.

    Here is a demonstration program

    #include <stdio.h>
    
    int main( void )
    {
        char s[100];
        
        scanf( "%99[^\n]%*c", s );
        puts( s );
        
        scanf( "%99[^\n]", s );
        puts( s );
    
        return 0;
    }
    

    In this case if to enter strings for example like

    Hello
          World
    

    then the output will be

    Hello
          World
    

    Another and more simple approach is to prepend the format string with a blank. For example

    scanf(" %[^\n]", toFind);
          ^^^^
    

    In this case all leading white space characters will be skipped.

    Here is a demonstration program.

    #include <stdio.h>
    
    int main( void )
    {
        char s[100];
        
        scanf( "%99[^\n]", s );
        puts( s );
        
        scanf( " %99[^\n]", s );
        puts( s );
    
        return 0;
    }
    

    In this case if to enter strings as shown above that is

    Hello
          World
    

    then the program output will be

    Hello
    World