0

What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.

#include <stdio.h>
#include <string.h>                                      

struct S {
  char str [10];
};

int main(void)
{
  int n;
  struct S strings [10];
  for (n = 0; n < 10; n++) {
    # fflush(stdout);
    scanf("%s", strings[n].str);
    if (strlen(strings[n].str) == 0)
      break;
    # getchar();
  }
  printf("done");
  return 0;
}

When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?

This sample solution works. Is there a difference in comparison to my code?

3
  • It's not the cause of your problem, but please just avoid using scanf; it's notoriously hard to use, and the way you're using it is susceptible to a buffer overflow. (And never use gets). c-faq.com/stdio/scanfprobs.html Commented May 29, 2012 at 10:48
  • scanf("%s", strings[n].str); expects at least one non-whitespace character. scanf will not return until it finds one. Commented May 29, 2012 at 15:43
  • @DanielFischer OK, note that I tried gets too which is used in sample solution by Chuck Allison too. Commented May 29, 2012 at 16:59

4 Answers 4

5

The enter key is not empty string, it is an ascii character or rather two characters a CR and LF (on Windows).

Sign up to request clarification or add additional context in comments.

2 Comments

end of line character depends, in *nix it is LF, Win: CRLF Mac CR , check : en.wikipedia.org/wiki/Newline
Yes I know that - but I was just talking about Windows - not that the others don't matter :-)
2

You shouldn't use strlen to find out if the input is empty. As others have said, when you press ENTER you get one or two characters sent to you.

You could instead check the first character in the string and see if it is '\n' or '\r'

Comments

1

scanf returns exactly what you've input... i.e. a crlf pair I'd imagine!

1 Comment

The word "returns" here is ambiguous.
1

The problem with using scanf is that it expects something, not an empty string. You solve this by using e.g. fgets instead of scanf:

if (fgets(strings[n].str, sizeof(strings[n].str), stdin))
{
    /* You got a string, it will contain the newline! */
}

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.