Boris Mutafov
Boris Mutafov

Reputation: 419

scanf three times in c doesn`t work?

Hello I have a homework from school to make a program that finds a word and replaces it with another in a text. I havent done char string until now and I have a little problem. I need to scan the Text, the find word and the replace word, but only the text scanf work and the other are just skipping..

 char w[10000];
char find[10000];
char replace[10000];
int l,c,b,diff,i,k,yes=0,vm;
printf("Text: ");scanf("%[^\n]s",w);
printf("\nFind: ");scanf("%[^\n]s", find);
printf("\nReplace: ");scanf("%[^\n]s", replace);

If you can say why the scanf for find and replace just skips I will be very thankful.

Sorry for bad English not my native language.

Upvotes: 0

Views: 505

Answers (3)

rcgldr
rcgldr

Reputation: 28826

This should work, since scanf should skip leading whitespace, including newlines.

char w[10000];
char find[10000];
char replace[10000];
    /* ... */
    printf("Text: ");scanf("%s",w);
    printf("\nFind: ");scanf("%s", find);
    printf("\nReplace: ");scanf("%s", replace);

Upvotes: 0

chux
chux

Reputation: 153517

scanf("%[^\n]s",w); has multiple problems:

  1. There is no need for s. "%[^\n]" is a complete format specifier. @unwind

  2. There is no input limit. Could use to cope with limits: char w[10000]; scanf("%9999[^\n]", w);

  3. The format does not consume anything is user enters Enter. w remains uninitialized and '\n' remains in stdin for the next scanf() which does the same thing.

    // NOT recommended
    scanf("%[^\n]%*c", w); This gets stuck on \n only input
    
  4. Nothing in scanf("%[^\n]",w); consumes the typical trailing '\n'. Code could use the following which also checks the scanf() result.

    if (scanf("%9999[^\n]", w) != 1) Handle_EOForEOLonlyInput();
    fgetc(stdin);
    

Suggest instead fgets()

char w[10000];
if (fgets(w, sizeof w, stdin) == NULL) Handle_EOForIOError();
// strip possible ending EOL if needed.
w[strcspn(w, "\n")] = 0;

Upvotes: 0

Gopi
Gopi

Reputation: 19864

Try this

printf("Text: ");scanf("%[^\n]%*c",w);
printf("\nFind: ");scanf("%[^\n]%*c", find);
printf("\nReplace: ");scanf("%[^\n]%*c", replace);

Just consume the newline character and get rid of s after [^\n] which says

Read till newline character is encountered


I would suggest you to use

fgets(w,sizeof(w),stdin);

which is much safer.

Upvotes: 1

Related Questions