...

View Full Version : Terminating a while loop with the letter q



Hayes
10-11-2011, 01:10 PM
Im playing around with C and I am trying to exit a while loop with the letter q but i cant seem to get it to work.


/*
Program: daystoweeks.c
Author: Danny Stones
Date: 11/10/2011
*/

#include <stdio.h>

int main(){
int day;
int week;
int days;

printf("Please enter the number of days: ");
scanf("%d", &day);

while (day!='q')
{
week = day/7;
days = day % 7;
printf("%d weeks and %d days", week, days);
printf("\nPlease enter the number of days: ");
scanf("%d", &day);
}
return 0;
}

Thanks
Danny

bobleny
10-11-2011, 03:06 PM
You are trying to compare an integer, day, to character, q.

I'm surprised this doesn't compile or blow up on you...

Divinityfound
10-11-2011, 05:21 PM
You can only compare integers with integers, doubles with doubles, and strings with strings... otherwise the while loop can never be matched up. Except maybe doubles and integers... but there are special rules with that.

Hayes
10-11-2011, 07:51 PM
Ok that makes sense thanks for the replys so how can I solve the problem? I am still clueless on the matter

bobleny
10-11-2011, 08:24 PM
You have a few options that I can see...

You could make 'q' a number, such as -1.


#include <stdio.h>

int main()
{
int day;
int week;
int days;

do
{
printf("Please enter the number of days: ");
scanf("%d", &day);

week = day/7;
days = day % 7;
printf("%d weeks and %d days", week, days);

}while(day != -1);

return 0;
}


You could make day a string and parse the string for a 'q'. If a 'q' is not found, then check each character in the string for a character between '0' and '9'. If they are characters between '0' and '9', then convert them into an int.

You could also create a main prompt like this:


What would you like to do?
0.) Calculate days
1.) Exit
Enter a number:


If they select 0, prompt them for the number of days. If they select 1, exit.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum