Issue with strings

Working on another simple program, I've come across an issue.
I've dumbed it down to highlight the issue itself:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<string>

using namespace std;
int main(){

int a;
char str[] = "543210";

     cout << str[2] << endl; //displays 3, as it should
     
     a = str[2]; 
     cout << a << endl; //displays 51

cin.get();
return 0;
}


Clearly I am not using strings correctly. Please can someone tell me what I am doing wrong :(
You're converting a char into an int, chars use the ASCII table where '3' happens to be 51.
If you want the integer to have the value 3 try something like this:
int a = '3' - '0';
I'm not sure I understand. I need the integer to be a value from the string. Is this possible?

I'm actually doing this problem: http://projecteuler.net/problem=8
This is my code, the reason I need it is for line 19:
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
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>

using namespace std;
int main(){

int start=0, end=4, a, b, max=0;
char string[1000];

ifstream in("test.txt");
in >> string;

while(end <= 999){
   a=string[start];
   b=start;
    while(b <= end){            
       a = a * string[b];
       b += 1;    
    }
      if(a > max){         
           max = a; 
      }
 end += 1;
 start += 1;
}
       
     
cout << string << endl;


cin.get();
in.close();
return 0;
}
It's pretty simple really, whenever you want to convert a digit in the form of a char to an int just subtract the ascii value for 0 like I showed you above.
Or in your code:
1
2
3
a = string[start]-'0';
...
a = a * (string[b]-'0'); 
Oh right, thank you very much!
I didn't get the correct answer straight away, but I made a very slight adjustment and got it right.

Thanks for helping to explain the issue!
Last edited on
Topic archived. No new replies allowed.