error with converting const char * to int.
Aug 25, 2012 at 4:12pm UTC
i am writing a code that should put some numbers in a const char * variable into an integer array but my ouputs are totally wrong. can someone tell me what i am doing wrong ?
this is my code:
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
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <time.h>
int main() {
clock_t start, end;
start = clock();
const char * number2="\
75\
95 64\
17 47 82\
18 35 87 10\
20 04 82 47 65\
19 01 23 75 03 34\
88 02 77 73 07 63 67\
99 65 04 28 06 16 70 92\
41 41 26 56 83 40 80 70 33\
41 48 72 33 47 32 37 16 94 29\
53 71 44 65 25 43 91 52 97 51 14\
70 11 33 28 77 73 17 78 39 68 17 57\
91 71 52 38 17 14 91 43 58 50 27 29 48\
63 66 04 68 89 53 67 30 73 16 69 87 40 31\
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23" ;
int number[100][100];
for (int j=0;j<15;j++) {
for (int i=0;i<((j+1)*3);i=i+3) {
number[j][i/3]=(number2[(((j)*3))+i]-48)*10+(number2[((j)*3)+i+1]-48);
}
}
for (int j=0;j<15;j++) {
for (int i=0;i<j+1;i++) {
std::cout<<number[j][i]<<" " ;
}
std::cout<<std::endl;
}
end = clock();
printf("\nTook %f seconds\n" , (double )(end-start)/CLOCKS_PER_SEC);
system("pause" );
return 0;
}
and this is my output: (note that this should show the numbers in the code)
75
34 41
41 -156 -152
-156 -152 18 35
-152 18 35 87 10
18 35 87 10 -16 24
35 87 10 -16 24 4 54
87 10 -16 24 4 54 51 -160
10 -16 24 4 54 51 -160 -158 -153
-16 24 4 54 51 -160 -158 -153 -160 -157
24 4 54 51 -160 -158 -153 -160 -157 88 2
4 54 51 -160 -158 -153 -160 -157 88 2 77 73
54 51 -160 -158 -153 -160 -157 88 2 77 73 7 63
51 -160 -158 -153 -160 -157 88 2 77 73 7 63 67 74
-160 -158 -153 -160 -157 88 2 77 73 7 63 67 74 34 24
Any ideas or suggestions ?
Last edited on Aug 25, 2012 at 4:21pm UTC
Aug 25, 2012 at 7:38pm UTC
Well, I'm not sure what you're doing to the numbers before you store them in the int matrix.
To help me understand what's going on... What would be desirable output from your program?
Aug 25, 2012 at 9:26pm UTC
Print 'number2', you will note `missing' spaces.
The traverse is incorrect, as you are stepping the same cells several times.
Aug 25, 2012 at 10:06pm UTC
I would do as ne555 suggests, and modify you first loop to print out what it's doing.
Note that a \ at the end of the line does not count as a char in a string. It's telling the preprocessor to splice the rows. So the compiler sees
1 2 3 4 5
75\
95 64\
17 47 82\
18 35 87 10\
20 04 82 47 65\
as
7595 6417 47 8218 35 87 1020 04 82 47 65
so the step of 3 your algorithm uses is not always correct.
And then you need to fix the way you work out the starting offset of your inner loop.
Last edited on Aug 25, 2012 at 10:08pm UTC
Topic archived. No new replies allowed.