Range-based loop problem

The loop won't break.


1
2
3
4
5
6
7
8
//string second="45670";
//string first="";
//int max=7; 	
   for(char temp:second)
	{
	first += temp;
        if(temp==(char)max) break; //not working
	}
max is an integer with value 7
temp is a character with value '7'

The value '7' corresponds to the value 55 in the ASCII. (google ASCII for details)
therefore the loop will not break when max is the character '7' but when the value of the character is 7

1
2
3
4
5
6
7
8
//string second="45670";
//string first="";
//char max='7'; 	 // added ' ', should work now
   for(char temp:second)
	{
	first += temp;
        if(temp==max) break; //not working
	}
are you thinking that (char)max is '7' ??
are you thinking that (char)max is '7' ??

Yep. Until now.


should work now

It probably will. But I need max to remain int.
then you can try int max = '7';
if that does not work cast the '7' to an int: int max = (int)'7';
max is an output from a function. It won't be 7 everytime.
but it will be a number between 0 and 9 right?
In this case you can do: if(temp==(max + '0')) break;
but it will be a number between 0 and 9 right?

Yep.
But I'm not sure if I understand what if(temp==(max + '0')) break; does.
Last edited on
Above line seems to work though I didn't understand how.
However, I need help with similar problem from another program.

1
2
3
4
for (int i = 0; i < line.length()-1; i++)
		{			
			int temp = line[i];
                }


How to make this work?
But I'm not sure if I understand what if(temp==(max + '0')) break; does.
in the ASCII all characters have a value.
values for 0-9 are consecutive, so to get the character-value of a number you simply need to add the value of '0' (which is equivalent to 48)

so if max = 7 then max + '0' = 55 = '7'

How to make this work?

What should it do?
Last edited on
"line" is a string and "temp" is an int.
It should assign the current char in "line" to temp.
so this char is a number (eg. '7') and you want to have it as int?

Same idea as above but in reverse order
int temp = line[i] - '0';
Thank you.
You're talking about the second table, right?
http://www.theasciicode.com.ar/
Topic archived. No new replies allowed.