1

I am trying to get: while(scanf("%c %c %d\n", &a, &b, &c) && (a!='\n')) to exit once a line is blank, eg the following:

a b 12
q w 4
g u 80

(exit)

Code:

while(scanf("%c %c %d\n", &a, &b, &c) && (a != '\n'))
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Fraser Langton
  • 471
  • 3
  • 12
  • 1
    Note that [trailing white space in a `scanf()` format string](https://stackoverflow.com/questions/15740024/) is almost invariably a very bad idea. – Jonathan Leffler Oct 14 '18 at 05:47
  • 3
    The `scanf()` family of file I/O functions does not respect newlines. If you need to detect newlines, do not use `scanf()` et al. (Using `sscanf()` is different — especially in combination with `fgets()`.) Note that `scanf()` would be happy if the `a`, `b` and `12` are on separate lines, with an arbitrary number of newlines between each; it would also be happy if all 9 fields were on a single line. It doesn't care — and the `\n` in the format doesn't mean "match a newline"; it means "match zero or more white space characters". – Jonathan Leffler Oct 14 '18 at 05:50

1 Answers1

3

To read a line, use fgets(). Then, if successful, parse the input string for '\n', expected a,b,c, or anything else.

//                          c  ' '  c  ' '  d   \n  \0
#define LINE_EXPECTED_SIZE (1 + 1 + 1 + 1 + 11 + 1 + 1)

char buf[LINE_EXPECTED_SIZE * 2]; // let us be generous with size.
while (fgets(buf, sizeof buf, stdin) && buf[0] != '\n') {
  char a,b;
  int c;
  if (sscanf(buf, "%c %c %d", &a, &b, &c) != 3) {
    // Note unexpected input
    fprintf(stderr, "Unexpected bad input '%s'\n", buf);
    break;
  }
  printf("a:'%c', b:'%c', c%d\n", a,b,c);
}

"\n" is rarely correct at the end of a scan() format. @Jonathan Leffler.


The above uses sscanf(...) != 3 to detect if 3 specifiers were matched. This will not detect if extra text was on the line. An advanced approach uses " %n" to scan optional following white-space and then note the scan offset at that point.

  // if (sscanf(buf, "%c %c %d", &a, &b, &c) != 3) {
  int n = 0;
  sscanf(buf, "%c %c %d %n", &a, &b, &c, &n);
  if (n == 0 || buf[n] != '\0') {
    // if scanning did not reach %n or extra text followed ...
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256