1

I am trying to read a string of characters in C: If I use gets, the compiler doesnt read my word, because it considers ENTER as being my string, I guess. I tried using

scanf("%*c") 

but then if i do that and type "flower", the variable stores the string "lower". If I use

scanf("%s",s)

then the compiler doesn`t store anything after I hit space. If I use

fgets(s,20,stdin)

I have the exact same problem as if I used gets. What should I do?

4
  • 2
    scanf("%*c") ?? missing second argument... Commented Jan 19, 2014 at 11:09
  • 2
    Please mind that it's not the compiler which reads your words. It's your program. Commented Jan 19, 2014 at 11:09
  • how do you print your string? Commented Jan 19, 2014 at 11:13
  • 2
    @GrijeshChauhan : the %*c will read and discard the character , which don't have to pass any arguments Commented Jan 19, 2014 at 11:14

3 Answers 3

1

Simply "remove" the newline if it's in the end of the string:

if (fgets(s, 20, stdin) != NULL)
{
    while (strlen(s) > 0 && s[strlen(s) - 1] == '\n')
        s[strlen(s) - 1] = '\0';
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 but I'd size_t len = strlen(s) rather than call strlen() 3x.
0

You can use getchar() and ungetchar() to solve this problem , Like this :

char c;   
while((c=getchar())<=' ');
ungetchar(c);

the code above will remove any unwanted spaces or enters before the string , then you can gets as you want

2 Comments

This code will also consume any char in the range CHAR_MIN to ' '. Maybe instead int c; while(isspace(c = getchar()));
There is : tab = 9 , line feed and carriage return = 10,13 and space = 32 , the others are control chars
0

scanf() does not read the string after space. In short, it reads continuous string but fgets() is defined to read characters(space also). In my compiler Dev-C++ & 64-bit operating system, fgets() is reading characters including space. Note space is also a character defined with ASCII value.

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.