1

I can't understand why this code is not working properly:

#include<stdio.h>

    int main()
{
    char string [100];
    int a;
    printf(">");
    scanf("%d", &a);
    printf(">");
    gets(string);
    printf("%s\n", string);
}

This is a little part from a program that I had to build and I can't understand why after getting the value into a by scanf() function, the program just skip or not reading properly the string by gets() function. If you copy the code into compiler and tries to run you will understand what I mean.

2 Answers 2

3

The %d specifier doesn't eat the newline (or other blanks for that matter). Try this:

scanf("%d ", &a);
         ^

That space makes scanf throw away all the blanks until a non-blank. Incidentally, your question is remarcably similar to this C FAQ.


  • Don't use gets, it's so bad it's not even in the language anymore. Use fgets instead
  • Don't trust anyone suggesting fflush(stdin) for your problem
Sign up to request clarification or add additional context in comments.

Comments

0

Whenever you need to read a sentence composed with spaces (after any scanf's), modify your the scanf to:

scanf(" [^\n]", mystring);
       ^ Space here.

Look your example:

#include<stdio.h>

int main(void)
{
    char mystring[100];
    int a;

    printf(">");
    scanf("%d", &a);

    printf(">");
    scanf(" %[^\n]", mystring);

    printf("Number:%d\nString: %s\n", a, mystring);

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.