1

I am trying to convert a string to an integer. I remember a teacher saying some thing like you must subtract 48 from it, but I am not sure, and when I do so, I get 17 as A's value, which is if I am correct 64. here is my code. any better way will be appreciated.

#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    cout << str[0] - 48;
    getch();
}
soheil
  • 23
  • 3

4 Answers4

1

A is not a digit, so how would you convert it to an int? Your code already works. For example, enter 5 and you'll see 5 as output. Of course it doesn't make any difference since you're just printing that value. But you could have stored in an int variable instead:

int num = str[0] - 48;

Btw, usually '0' is used instead of 48 (48 is the ASCII code of 0). So you can write str[0] - '0'.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • And the reason for using `'0'` rather than `48` is that some systems do not use ASCII. There's no reason to build in unportability here. – Pete Becker Oct 31 '13 at 16:19
1

A simple and typesafe solution using only C++ facilities is the following approach:

#include <iostream>
#include <sstream>

int fromString(const std::string& s)
{
  std::stringstream stream;
  stream << s;

  int value = 0;
  stream >> value;

  if(stream.fail()) // if the conversion fails, the failbit will be set
  {                 // this is a recoverable error, because the stream
                    // is not in an unusable state at this point
    // handle faulty conversion somehow
    // - print a message
    // - throw an exception
    // - etc ...
  }

  return value;
}

int main (int argc, char ** argv)
{
  std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think)
  std::cout << std::stoi("123") << std::endl; // C++ 11

  return 0;
}

Note: that in fromString() you should probably check to see if all characters of the string actually form a valid integral value. For instance, GH1234 or something wouldn't be and value would remain 0 after invoking operator>>.

EDIT: Just remembered, an easy way to check if the conversion was successful is to check the failbit of the stream. I updated the answer accordingly.

thokra
  • 2,874
  • 18
  • 25
0

There is the atoi function that converts a string to an int but I am guessing you want to do this without library functions.

The best hint I can give you is to take a look at an ascii table and remember that:

int c = '6';
printf("%d", c); 

Will print the ascii value of '6'.

doron
  • 27,972
  • 12
  • 65
  • 103
0

There's a function called atoi in cstdlib that does it most simply: http://www.cplusplus.com/reference/cstdlib/atoi/

int number = atoi(str.c_str()); // .c_str() is used because atoi is a C function and needs a C string

The way these functions work is along these lines:

int sum = 0;
foreach(character; string) {
    sum *= 10; // since we're going left to right, if you do this step by step, you'll see we read the ten's place first...
    if(character < '0' || character > '9')
         return 0; // invalid character, signal error somehow

    sum += character - '0'; // individual character to string, works because the ascii vales for 0-9 are consecutive
}

If you gave that "23", it goes 0 * 10 = 0. 0 + '2' - '0' = 2.

Next loop iteration: 2 * 10 = 20. 20 + '3' - '0' = 23

done!

Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60