[try Beta version]
Not logged in

 
Repeat do while loop if there is an character

Mar 31, 2011 at 2:22pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <conio.h>

int nx

;void main()
{
	std::cout << "hi\n";
std::cout << "somerandomrpogramk";
do {
std::cout << "Type 5:  ";
std::cin >> nx;
} while (nx != 5 && nx == "B" ); //Any letter instead of B
std::cout << "thanks! :D";
_getch();
}


I want the loop to repeat if there is a letter in nx, because 5a, 5x, 5b, etc.
will work too. How do I do that?
Apr 2, 2011 at 11:41am
bump.
Apr 3, 2011 at 4:23pm
bump again.
Come on, it can't be that hard.
Apr 3, 2011 at 5:55pm
Well as far as I know (because I'm only a beginner too) "nx" can never be a letter, because the nx variable type is an int. This means that nx can only store integer values in that scope.
If you made it a char instead of an int then it would be able to store letters and numbers, but it would only be able to store one at a time (so if you try and store 'ab' in a char, it will only store 'b').

Also, doesn't your compiler throw a spazz if your main function doesn't return an int?
Last edited on Apr 3, 2011 at 6:30pm
Apr 3, 2011 at 7:09pm
i'm not shure but maybe problem is here:

YOURE CODE:
1
2
3
4
5
6
do {
std::cout << "Type 5:  ";
std::cin >> nx;
}
 while (nx != 5 && nx == "B" ); /* this won't work because  nx == "B" 
will not be checked cos expesion before && is true and it should be 'B' I think :) */


MY CODE
1
2
3
4
5
do {
std::cout << "Type 5:  ";
std::cin >> nx;
}
while (nx != 5 );
Last edited on Apr 3, 2011 at 7:17pm
Apr 4, 2011 at 8:55am
The DooD, no, since it's VOID main(), it doesn't require return 0, that would be if I'd put INT main() instead, that would require return 0. Since it's not a complicated program I don't have to inform the system about the result of my program.

Thanks, changing it to char helped. However if I type 5k or k5 or any other letter (not number)
it prints "Type 5: " two times. How do I prevent that?
Apr 4, 2011 at 9:19am
void main is non-standard, C++ requires int main.
As The DooD said, you need to read a character if you want to check whether it's a letter ( using isalpha function )
If instead want to read an integer and skip invalid input (like letters or any other non-numeric character), see http://www.cplusplus.com/forum/articles/6046/
Topic archived. No new replies allowed.