user1426474
user1426474

Reputation: 11

getting a string from the user after getting int in C language

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.

Upvotes: 1

Views: 340

Answers (2)

Rafael Bluhm
Rafael Bluhm

Reputation: 41

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;
}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182649

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

Upvotes: 3

Related Questions