C++ and Loops??? (help appreciated)

Joined
Aug 29, 2003
Messages
2,874
Reaction score
2
I've run into a problem dealing with characters.


What I want is for the user to enter in one of two values:

'p' for pounds
'k' for kilograms
...and if they enter neither 'p' or 'k', the program repeats: asking the user to re-enter a value again.

The question is, how would I go about setting that up in C++?

I know I will need to use a loop of some kind, but my attempts so far have failed. I can't get the program to read the inputs properly, and as a result my program crashes. Something about the characters that needs fixing up.

This portion of my program is supposed to do a conversion from metric units to the English system. I have everyting completed, except this small part.

If they choose pounds, the program should proceed in the English system.
If the user chooses kilograms, the program should proceed in the metric system.
And, of course, if they fail at correctly choosing pounds or kilograms, the program should ask them to try again.





I'll likely be laughing at this once this problem gets figured out. Having a bit of a brain cramp today. :p
 
what did you try?
make a bool for valid input, let the user enter a letter, check the letter, if it's neither k or p, set valid to false, start a loop and do the same check, keep the loop going as long as valid is false.

A do while loop is probably your best bet.
 
Thanks for the quick reply hasan.

I haven't learned any bool commands yet (Probably why I'm having difficulty eh).

I'll retry the do loop and post the result if I encounter problems.
 
you don't have to use a bool, just put do { } while(input != 'k' || input != 'p');
 
Here it is...so far (edited for better assistance :) ):

Code:
#include <stdio.h>
main()
{
	float start;
	char type;
	char P, K;
				printf("Enter the conversion type.\n");
				printf("Enter either 'P' for pounds or 'K' for kilograms.\n");
				scanf("%s", &type);
				do	{
					printf("Enter the starting point.\n");
					scanf("%f", start);
					} while (type == P || type == K);
				printf("The starting point is %f.", &start);
	return 0;
}

Now the problem I'm having is, even though I'm not entering 'P' or 'K', the program still moves to the second printf statement (even though the loop is false).

EDIT: I'm having problems changing the code after I posted, but there should be an '&' in the second scanf statement
EDIT 2: Now that I look at it, even if the program worked, it wouldn't make sense. :LOL: Back to the drawing board.
 
Here's the revision:

Code:
#include <stdio.h>
main()
{
	float start;
	char type;
	char P, K;
				printf("Enter the conversion type.\n");
				printf("Enter either 'P' for pounds or 'K' for kilograms.\n");
				scanf("%s", &type);
				do	{
					printf("Input is invalid.\n");
					scanf("%s", &type);
					} while (type != 'P' || type != 'K');
				printf("Enter the starting point.\n");
				scanf("%f", &start);
				printf("The starting point is %.2f.", start);
	return 0;
}

But now I can't even get the loop to exit when I enter 'P' or 'K'. :( :rolling:
 
strcmp is where it's at baby

#include <stdlib.h>

//if they match you get 0
strcmp(type, "P") == 0
 
nutcrackr said:
strcmp is where it's at baby

#include <stdlib.h>

//if they match you get 0
strcmp(type, "P") == 0

I get an error when I try that. :(

I have never heard of strcmp before...
 
heh that's in C

in any case I'd skip the do just use a while loop:

Code:
char temp;
//use this outer bracket so that the loop variables are only temporary
{
	bool flag = true;
	while(flag)
	{
		cout<<"Please Enter [P]ounds or [K]ilograms\n>";
		cin>>temp;
		if(temp == 'k' || temp == 'K')
		{
			flag = false;
		}
		else
		{
			if(temp == 'p' || temp == 'P')
			{
				flag = false;
			}
		}
		if(flag)
		{
			cout<<endl<<"Please use	[P]ounds, or [K]ilograms\n>";
		}
	}
}
//here you can use the temp value to determine which to use,
or you can insert that logic into the loop.
//you might need to flush the input at the start of the loop
 
Cunbelin said:
heh that's in C

in any case I'd skip the do just use a while loop:

Interesting...

things like cin or cout seem quite advanced given that I'm new to this.

Also when I enter it into Microsoft Visual C++, I get an error.

(4) : error C2447: missing function header (old-style formal list?)

Which header am I to include?
 
lol, my mistake.

try instead of
Code:
input != 'k' || input != 'p'
make it
Code:
!(input == 'k' || input == 'p')

why? in the first case, input has to equal both 'k' and 'p', which is ipossible!!!

btw, strcmp is for strings, in this case it's a single character, so it's not needed, and it won't work aswell, because string are terminated with '\0' where as single characters are not.
 
THANKS A MILLION HASAN!!!


You have made me happy. :) :)

Now the rest of my program should work!!



EDIT: It appears that it STILL only accepts 'P' first. If you enter 'K', it still reads as invalid. We're almost there. :imu:
 
#include <iostream> should cover it. cin and cout are the equivalent to printf and scanf, you use the bit shift operators to move data from them or to them. MSDN isn't spitting out what I want on search so you might try the internal help library.
 
OK, the problem is it reads the first input as invalid no matter what. After the first input, then hasan's changes work.

Is there a way to ignore the first value as invalid...or something like that?

EXAMPLE:

Enter 'P' OR 'K'
(I enter 'P')
THE ENTRY IS INVALID
(I enter 'P' again)
THE ENTRY HAS BEEN ACCEPTED


This would be the last bug in the road. Thanks again for the assistance guys. :D

EDIT: Sorry Cunbelin, you technique is just too different/advanced to what I'm used to. Even with your pointers, I'm still getting errors with your method. These errors are likely coming from me anyway. :p
 
look at the code:
Code:
scanf("%s", &type);
do
{
	printf("Input is invalid.\n");
	scanf("%s", &type);
} while (type != 'P' || type != 'K');
you ask for input, then enter a loop: the loop has the following:
print a messege saying the input is invalid
take the input
evaluate

you see what's wrong?

P.S. where in canada do you live?
 
hasan said:
look at the code:
Code:
scanf("%s", &type);
do
{
	printf("Input is invalid.\n");
	scanf("%s", &type);
} while (type != 'P' || type != 'K');
you ask for input, then enter a loop: the loop has the following:
print a messege saying the input is invalid
take the input
evaluate

you see what's wrong?

P.S. where in canada do you live?

I'll take a stab at it.

It looks like any value that is entered will be associated with the phrase "Input is invalid" before the conditions of the loop can be executed.
As for setting it up to 'void' the first output statement, I am at a loss. :(

P.S. I live in Keswick (birthplace of NHL goaltender Curtis Joseph). Approximately 40-60 minutes driving distance from Toronto, Ontario.
:cheers:
 
yes the messege "input is invalid" will always be excuted after the first input regardless of what you enter.

I think you should know the if structure at this point. just check for input BEFORE the while loop, and make the loop INSIDE the if structure.

also, I think at this point it won't matter anymore if you do a while or a do while.
 
Code:
#include <stdio.h>
main()
{
	float start;
	char type;
				printf("Enter the conversion type.\n");
				printf("Enter either 'P' for pounds or 'K' for kilograms.\n");
				scanf("%s", &type);
				
				do	{
					if (!(type == 'K' || type == 'P'))
					{
						printf("Input is invalid.\n");
						scanf("%s", &type);
					}
					else
						break;
					} while (!(type == 'K' || type == 'P'));

				printf("Enter the starting point.\n");
				scanf("%f", &start);
				printf("The starting point is %.2f.", start);
	return 0;
}

It works great now. Thanks for the help. :bounce:

EDIT: Trying nietzsche's theory
EDIT2: Good call nietzsche. It makes more sense to use %c since I'm only dealing with one single character and not an entire string.
 
Hmm, the title says "C++" yet we're using printf, and including "<stdio.h>" instead of "<stdio>".

/pedant
 
we11er said:
Hmm, the title says "C++" yet we're using printf, and including "<stdio.h>" instead of "<stdio>".

/pedant

It's probably for simplicity reasons. The stuff you guys were giving me seem more efficient. It will be revealed to me in time; another month-and-a-half of classes and I should learn everything I need to know.
 
geez yall are giving him a SUPER complicated version of that. that or C++ is just retarded. I know thisworks with C# ( which is C++ and VBs lovechild - very close in most respects) the loop and exit wit ha break is like... 1 line of code. none really cause its part of other stuff. somehting like this surely translates to C++


while(true)
{
if (some conditions.. I dunno, its your proggie)
do some stuff;
//blah blah blah, all your calculations
if( exit condition.. use a null or whatever makes you happy)break;
}




if/then all your stuff.. then tell it that a null string will exit .. and do a if for it, followed by break. its all up there. this works in C# so surely theres something very similar if not identicle in C++ (unless it sucks that is). try that.

haha. oh man. I didnt even notice the true canadians post a couple up that beat me to the break. oh well. I took the time to type this crap, I aint deleting it. listen to that guy. he knowsthis stuff.
 
EDIT: Looks like the window for help with this problem is long passed, but hey, this could still be of some help to you...

Hey Canadian, I noticed a couple things that could be cleaned up with the latest version of the code you posted.

One is that you're stating the valid condition for type twice, and it need only be stated once. If you ever need to add a new unit to your system, then you'd only have to change one thing instead of two.

Just to be clear on this, for later reference: if var is a character array, then you NEVER want to use scanf("%s", var). Instead, use something like scanf("%10s", var), as this will guarantee that at most 10 characters are read and copied into var. Better yet, use the standard string class, and cin >> into that string, and you'll never have to worry about overflows again.

I hate to be too precise about this, but declaring main() without a return type isn't valid C++. In fact, main must only return an int (which you're doing in your code anyway). The fact that some compilers support this doesn't make it ok.

A good way to do what you want is the following:

Code:
#include <iostream>
using namespace std;

int main()
{
	float start;
	char type;

	cout << "Enter the conversion type.\n";
	cout << "Enter either 'P' for pounds or 'K' for kilograms.\n";
	cin >> type;
	while( !(type == 'K' || type == 'P') ) {
		cout << "Input is invalid.\n";
		cin >> type;
	}

	cout << "Enter the starting point.\n";
	cin >> start;
	cout << "The starting point is " << start << ".\n";
	return 0;
}
This, of course, doesn't actually fix the precision to two decimal places.

Or, if you absolutely must use C I/O, then have at it:
Code:
#include <stdio.h>

int main()
{
	float start;
	char type;

	printf("Enter the conversion type.\n");
	printf("Enter either 'P' for pounds or 'K' for kilograms.\n");
	scanf(" %c", &type);
	while( !(type == 'K' || type == 'P') ) {
		printf("Input is invalid.\n");
		scanf(" %c", &type);
	}

	printf("Enter the starting point.\n");
	scanf("%f", &start);
	printf("The starting point is %.2f.\n", start);
	return 0;
}

Note the leading space in the first scanf's format-string, which by convention eats any leading whitespace before reading the character (this is cin's behavior by default).

You'll want to use C I/O only a) if your programming class requires it, b) if what you want to do happens to be a lot easier with C I/O, or c) if you're super concerned about performance. It's a lot easier to write bug-free, maintainable code with the C++ facilities.

Sorry if I seemed too nit-picky, but I just get really excited when I get to help people with programming, since I love programming. :)
 
char C;
for(C='\0';C != 'p' && C!= 'k';scanf("%c",C));


that will ask for a character until p or k is entered. you can add some print statements:

char C;
printf("Enter p for pounds or k for kilograms: ");
for(C='\0';C != 'p' && C!= 'k';scanf("%c",C))
printf("Invalid entry, please re-enter: ");
 
whoops! change for(C='\0';C != 'p' && C!= 'k';scanf("%c",C))
to for(C='\0';C != 'p' && C!= 'k';scanf("%c",&C))

missed the amperstance (the "&")
 
I haven't read the entire thread so sorry if this has already been said.

Remember computers are stupid and do instructions one after another. Saying that here is what I'd do:

Code:
#include <stdio.h>

int main()
{
	float start;
	char type;

             do
             {
	      printf("Enter the conversion type.\n");
	      printf("Enter either 'P' for pounds or 'K' for kilograms.\n");
	      scanf(" %c", &type);
             }while(type != 'K' || type != 'P')
		
	printf("Enter the starting point.\n");
	scanf("%f", &start);
	printf("The starting point is %.2f.\n", start);
	return 0;
}

A do while loop will run at least once, you want that.

You could also throw in an if after scanning the entry to output an error message if you want.
 
Back
Top