Need to convert from ascii dec to char

I am writing a program to validate an isbn number. In my code I am instantiating an array of chars. Then I am trying to read in what the user types in (isbn number) and assign it to the array. I need to be able to maniupulate (add and multiply) some of the numbers in the isbn, but when I try to print out the first value in the array 'isbn' it gives me the ascii dec of the number, instead of the number itself. When testing this out so far, the isbn number I used starts with a '0' and when I printed it out, it printed out '48' instead of 9 (48 is the dec number on the asii table). I'm not really sure what that dec is anyway, so if someone could explain this and explain how to get the actual numbers from the isbn number instead of the dec value I would greatly appreciate it. Thank you.

This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string> 
using namespace std;

int main(int argc, const char * argv[])
{
    char isbn[0];
    
    cout << "Enter ISBN: ";
    cin >> isbn;
    
    
    int isbnSum = isbn[0];
    cout << isbnSum << endl;
    cout << isbn << endl; 
 
    
    return 0;
}
Last edited on
char isbn[0]; creates an array of zero length, which you give to cin to fill, which should result in a segfault. Use an std::string instead of char.

To get numbers from a string, you can use atoi: http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

Or you can subtract '0' from each character of the string.

1
2
3
string str = "123456789";
int dec = str[4]; // will be 53 (dec for '5')
int num = str[4] - '0'; // subtracts '0' (dec 48) from '5' (dec 53), leaving 5 
Last edited on
Firstly edit your post so it uses code tags - the <> button on the right.

Next, what are try achieve with this:

char isbn[0];

How many chars will that hold? Why are you not using strings?

What you need to realise is that a char is just a small int. '0' is a user friendly representation of the decimal (integer) 48. So to print '0' or 'a' or 'Z' or whatever the type needs to be char.

cout << isbn << endl;

That doesn't do what you think. It prints the address of the array (a pointer or memory address). IF isbn was a string - it would work.

I think you need to read up a bit on types.

http://www.cplusplus.com/doc/tutorial/


There is a lot of good info in the documentation / reference section.

HTH
If I make isbn a string instead of an array, then how can I grab one number out of it and use it to add or multiply with other numbers?
Topic archived. No new replies allowed.