简体   繁体   中英

Variable length input of a character or a number using scanf and a loop in C

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: Eg 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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM