0

I'm looking to get the user's input all at once by using scanf in a while loop. The input will most likely be in a form that contains both characters and float numbers: E.g. 2 + 3.4 * 5, and I want to store the number and character into a separate array (for further processing via functions)

This is what I've come up with so far:

while (scanf(" %f", &num1) == 1 || scanf(" %c ", &op) == 1) {
    printf("%f ----> %c", num1, op);
}

but any character that I enter is automatically converted to a 'u' and my numbers are printed twice if I enter more than one number. Furthermore, I'm not sure how to get out of the while loop. (I tried throwing a break below printf, but that only allowed two inputs to be read)

Any idea how I can make this work?

Tori Henri
  • 734
  • 2
  • 9
  • 20
  • Try http://stackoverflow.com/questions/22149775/using-scanf-to-read-in-an-equation-of-random-length/22154595#22154595 – chux - Reinstate Monica Mar 04 '14 at 00:46
  • Trouble with this approach is that by the time code prints, it has lost which `scanf()` worked. BTW: `" %f"` same as `"%f"`. – chux - Reinstate Monica Mar 04 '14 at 00:48
  • @chux The only problem with that question, is that all of the answers are putting the input into a string. If i wanted to do that, I could just use gets, could I not? What i'm trying to do, is separate each number then character, one at a time and send each through a function (depending on if it's a character or number) Does that kind of make more sense? – Tori Henri Mar 04 '14 at 01:11
  • 1) Yes, you could read the whole line at once. And 2) it makes some sense, but not with this approach. `||` will execute the left only (if true), or the left and right (if left is false). When code does `printf("%f ----> %c", num1, op)`, we do not even know if `num1` or `op` was ever successfully scanned (one of them was, but not the other). (BTW, gets() is gone in modern c, fegts() is closest alternative.) – chux - Reinstate Monica Mar 04 '14 at 02:41
  • Your approach _may_ work if 1) use `&&` instead of `||` and 2) assume input will always be a number followed by an operator. This will not work though for `2 + 3.4 * 5`. Let me try a proposed solution soon. – chux - Reinstate Monica Mar 04 '14 at 02:44
  • Maybe you want something closer to `while (1) { if (first_scan_number_works()) print_number(); else if (second_scan_op_works()) print_op(); else break; }` – chux - Reinstate Monica Mar 04 '14 at 03:05

1 Answers1

0

Suggest reading into a line via fgets(), but if one wants to read dirclty from stdin, then scan both number and opcode at once, but print based on what was read.

int cnt;
while ((cnt = scanf("%f %c", &num1, &op)) > 0) {
  printf("%f", num1);
  if (cnt > 1) printf(" ----> %c ", op);
}
printf("\n");
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256