Thread: Ideas for error checking from command line

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by NuNn View Post
    Thank you that helped for the infinite loop issue, is there a way to make scanf() stop waiting if not enough inputs were entered and if there are too many inputs scanf() just ignore's the extras correct?
    My code works also to clean out extraneous "valid" input. It does not solve the problem of only one or two inputs when you expect 3. To solve that, you will need to read a string (for example fgets()) and then use sscanf() to read from the string - that ALSO solves the problem of dealing with "bad" input nicely, so you don't actually need any loops or such).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  2. #2
    Registered User
    Join Date
    Nov 2007
    Posts
    96
    I have updated my file and it seemed to be working fine, however there is a minor glitch:

    Code:
    int main() {
    	double a, b, c, x1, x2;
    	int qret, count;
    	char line[30];
    
    	while(1) {
    		count=0;
    		printf("Enter variables for quadratic equation (Enter 'q' or 'quit' to exit):  ");
    		fgets(line, 30, stdin);
    	
    		if((strncmp(line, "quit", 4) > 0) || (strncmp(line, "q", 4) > 0))
    			return 0;
    		else
    			count = sscanf(line, "%lf %lf %lf", &a, &b, &c);
    
    		if(count != 3) 
    			printf("Invalid Input: Format Is <double> <double> <double>\n\n");		
    					
    
    		else if(count == 3) {
    			qret = qsolver(a, b, c, &x1, &x2);
    			printf("Error Value:  %d\n", qret);		
    			printf("X1 = %lf   X2 = %lf\n\n", x1, x2);
    		}
    	}
    	return 0;
    }
    for some reason the count returned by sscanf is 30 some of the time and im unsure as to why this is. I see that my array size is 30, but shouldn't sscanf() return the number of correctly read items?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Project ideas.
    By Wraithan in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 04-25-2009, 03:29 PM
  2. Ideas, how do you get them? xD
    By Akkernight in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 01-22-2009, 03:53 AM
  3. cool ideas for a game
    By Shadow12345 in forum Game Programming
    Replies: 7
    Last Post: 05-18-2004, 08:37 PM
  4. idea's idea's idea's
    By mithrandir in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 04-29-2002, 12:30 AM
  5. Small app ideas
    By dirkduck in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 02-15-2002, 08:57 PM