1

I'm looking to read in several data points from the user via stdin and scanf().

However, if the user wishes to indicate invalid data, denoted by a *, this would violated the expected format (%f, %d, etc), and as I understand it, cause scanf() to return an error.

The way I conceived to deal with this is to read the input from stdin as a series of strings, check these for *, and then deal with that accodingly. This seems very naive and messy, and I was wondering if there was a cleaner way to accomplish this.

Please note, I am working in a very limited environment, so POSIX/3rd party solutions will not apply. ANSI C only :(

4
  • 3
    You need to read the input into a buffer and attempt to parse it repeatedly until you succeed. There is a lot of theory on doing this that is usually presented in "compilers" course. If you don't want to go that route, you might use fgets or getline to read the input into a buffer and then process that a few time to see how it works, but it will get complicated and slow in a hurry unless there are only a limited number of possible correct parsings. Commented Feb 18, 2013 at 20:46
  • One word: fgets(). (OK, maybe two, strchr() applies as well.) Commented Feb 18, 2013 at 21:46
  • 1
    Don't use scanf. c-faq.com/stdio/scanfprobs.html Commented Feb 18, 2013 at 22:50
  • Was hoping for something elegant and simple, but it looks like @dmckee's response is the best way to go Commented Feb 19, 2013 at 14:08

1 Answer 1

1

In general I recommend fgets() for input, but ...

There is a simple scanf() solution if you oblige the user to use "nan" for invalid data. By entering "nan" (not-a-number), you solve 3 issues: this posted question, how to represent invalid data within your code and how to print out invalid data.

Example: Read 2 data points per line

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
...
double f1, f2;
int i;
f1 = f2 = atof("NaN");
i = scanf("%lf %lf\n", &f1, &f2);
if (i != 2) {
  // Handle input error
}
if (isnan(f1)) { 
  // Handle invalid f1
}
...
Sign up to request clarification or add additional context in comments.

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.