-
Do While Looping Help
I'm writing a simple program for my chemistry class that does ideal gas law conversions. I have successfully gotten the program to do the conversions and calculations but I cannot get it to loop. I would like it to ask the user, "Do you need to perform another conversion?". If the user answers yes, it loops, if the answer is no, it stops. I'm pretty new to all this (surprise, surprise eh?) so bare with me. Here is the code I have thus far. Any help would be greatly appreciated!
Code:
char yes;
int main()
{
do
{
float pressure;
cout<<"Define P: ";
cin>>pressure;
float volume;
cout<<"Define V: ";
cin>>volume;
float nofmoles;
cout<<"Define n: ";
cin>>nofmoles;
float temperature;
cout<<"Define T: ";
cin>>temperature;
if(pressure==0)
cout<<"Pressure equals "<<(nofmoles*0.08206*temperature)/volume<<" atms.";
if(volume==0)
cout<<"Volume equals "<<(nofmoles*0.08206*temperature)/pressure<<" liters.";
if(nofmoles==0)
cout<<"Number of moles equals "<<(pressure*volume)/(0.08206*temperature)<<".";
if(temperature==0)
cout<<"Temperature equals "<<(pressure*volume)/(0.08206*nofmoles)<<" degrees K.";
cout<<"
";
cout<<"Do you need to perform another conversion? ";
cin>>question;
}while(question==yes);
return 0;
}
Thanks in advance!
-
Before any replies pop up telling me this forum is not for homework help, I am writing this program on my own accord and is in no way homework. I just figured this would be a simple program to learn with as it includes basic C++ code.
Thanks again :)
-
The way you have it is, char question;. This is fine, but a single char only holds one character.
So you have two options, have the user enter either 'Y' or 'N' like:
Code:
char question;
// ...
cout << "Go again?(Y/N): ";
cin >> question;
}
while(question == 'Y' || question == 'y');
Or, you can have a character array:
Code:
char question[5];
// ...
cout << "Enter yes to do it again: ";
cin.getline(question,5);
}while(strcmp("Yes",question));
You need the cstring header file for strcmp, and you use the getline() member function of cin for char arrays, that way you read the amount of characters you want.
Also you need to have 1 extra element in your array for a null terminator.
Hope that helps.
-
Worked like a charm CheesyMoo, thanks for the quick help!
-
just to mention, we're willing to help with homework, but we won't write the program for anyone.