atoi related question

This is a discussion on atoi related question within the C++ Programming forums, part of the General Programming Boards category; the below program ends when a letter is input because any non numerical value is converted to 0. What if ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    atoi related question

    the below program ends when a letter is input because any non numerical value is converted to 0. What if i want to be able to type in '0' and the program not to end . Can anyone help me out?

    Code:
    int main(void)
    {
    	char num[80] = {0};
    	int num1 = 0;
    	do
    	{
    		cin >> num;
    		num1 = atoi(num);
    		cout << num << '\n';
    	
    	}while(num1 != 0);
    
    	return(0);
    }

  2. #2
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    Code:
    #include <cctype>
    
    int main(void)
    {
    	char num[80] = {0};
    	int num1 = 0;
    	do
    	{
    		cin >> num;
    		num1 = atoi(num);
    		cout << num << '\n';
    	
    	}while(isdigit(num));
    
    	return(0);
    }

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main(void)
    {
      int i;
      
      while (!(cin >> i ))
      {
        cerr <<"Bad number " << endl;
        cin.clear();
        while ((i = cin.get()) != '\n' && i != EOF);
      }
      
      cout <<"Number was " << i <<endl;
      
      return(0);
    }
    
    /*
     Output
    
    abc
    Bad number
    1
    Number was 1
    
    
    0
    Number was 0
    
    
    567abc
    Number was 567
    
    The last run left abc in the input buffer. Is this what
    you want to do when a user enters something like that?
    
    */
    Also:
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  2. Yacc question related to %type
    By g_p in forum Tech Board
    Replies: 0
    Last Post: 05-31-2007, 09:55 AM
  3. Question related to getpid and getppid
    By g_p in forum C Programming
    Replies: 4
    Last Post: 12-18-2006, 10:35 AM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 08:22 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21