User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 397,752 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,523 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser:

C and C++ Timesaving Tips

Join Date: Apr 2004
Posts: 3,462
Reputation: Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light 
Rep Power: 16
Solved Threads: 138
Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: C and C++ Timesaving Tips

  #14  
May 13th, 2005
Reading an Integer

This is in many FAQs elsewhere, so this is just my repackaging of it here.

C Version
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   char response[32];
   /*
    * Prompt for input.
    */
   fputs ( "Enter your number: ", stdout );
   fflush ( stdout );
   /*
    * Read user response.
    */
   if ( fgets ( response, sizeof response, stdin ) != NULL )
   {
      /*
       * Attempt to convert user's response into an integer using strtol. The
       * second parameter to strtol allows for greater error checking if used.
       */
      int value = strtol ( response, NULL, 10/* radix or base */ );
      /*
       * No error checking was done, but attempt to display integer value.
       */
      printf ( "value = %d\n", value );
   }
   return 0;
}

/* my output
Enter your number: 12345
value = 12345
*/
C++ Version
#include <iostream>
#include <string>
#include <sstream>

int main(void)
{
   std::string response;
   /*
    * Prompt for input.
    */
   std::cout << "Enter your number: ";
   /*
    * Read user response.
    */
   std::cin >> response;
   /*
    * Attempt to convert user's response into an integer using a stringstream.
    */
   std::istringstream convert(response);
   int value;
   if ( convert >> value )
   {
      std::cout << "value = " << value << std::endl;
   }
   return 0;
}

/* my output
Enter your number: 456879
value = 456879
*/
 
All times are GMT -4. The time now is 3:29 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC