sorta stuck...

so im writing a program to validate isbn, all is good except when i use atoi()with my char* it converts the whole isbn instead of just one number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
.bool isbnChk(std::string isbn)
{
//int strElem = 0 ;
/*process the string, stripping non-digits and non 'X' */
for( int strElem = 0 ; strElem < isbn.length() ; strElem ++)
{/*use end iterator*/
if(!isdigit(isbn[strElem]) && toupper(isbn[strElem]) != 'X')
{
isbn.erase(strElem, 1) ;
--strElem ;
//isbn.push_back() ;
}
}

/*create iterator to end of string*/
std::string::reverse_iterator isbnEnd = isbn.rbegin() ;
std::cout << *isbnEnd << std::endl ;
//char *endS = isbn.c_str() ;
 char  *isbnPtr = new char [isbn.length() + 1] ;
std::strcpy(isbnPtr, isbn.c_str()) ;


const int last10 = 9 ;
const int last13 = 12 ;

/*determine if isbn10 || isbn13 if neither throw exception*/
if(isbn.length() == 10)
{
// store and erase last digit as chkDigit if == x then 10
int chkDigit = 0 ;
	if(toupper(isbn[9]) == 'X')
	{
	chkDigit = 10 ;
	printf("%d\n",chkDigit) ;
	}
	else
	{ 
	isbnPtr += last10 ;
	chkDigit = atoi(isbnPtr) ;
	std::cout << "atoi in else : " << atoi(isbnPtr) << std::endl ;
	isbnPtr -= last10 ;
 	printf("in else %d\n",chkDigit) ;
	} 
	//std::cout << *(isbnPtr +1)  << std::endl ;

	
int mult = 1 ; // isbn multiplier, will incriment
int chkSum = 0 ;

char is[14] ;
memcpy(is, isbnPtr, sizeof(isbnPtr)) ;

for(int strElem = 0 ; strElem < last10 ; strElem++)
{
printf("chkSum %d\n", chkSum) ;
chkSum += atoi(isbnPtr) * mult ;
std::cout << "atoi: " << atoi(isbnPtr) << std::endl ;
std::cout << "ISBN: " << *isbnPtr << std::endl ;
++isbnPtr ;
++mult ;
}
chkSum %= 11 ;

printf("%d\n",chkSum) ;
isbn.erase(isbn.length(), 1) ;
} /*end if(isbn10)*/

else if(isbn.length() == 13)
{

} /*end if(isbn13)*/
else
{
// shoot user
}
//std::cout << isbn << std::endl ;
//printf("%s\n",isbn) ;
// strip of nonnum





}
Last edited on
It's true that atoi() convert the whole string to number.
Could you make it more clearly?
Is your string contains many numbers which separated by whitespace character?
Last edited on
I realize that, however is there a way to make isbnPtr point to only one?
the string is stripped of all non-digits, then converted into a cstring. I need to access one element at a time so i can convert to int's and deal with one at a time.
Then use the array operator [] to select each character in your string. Now you have a char and to make it int, subtract it to '0'. Thus:
1
2
3
char testString[] = "12";
cout << testString[0] - '0' << endl;
cout << testString[1] - '0' << endl;


The result is:
1
2
1
2

Last edited on
Topic archived. No new replies allowed.