Program cannot exit this while loop

Below is my code. It seems that I cannot exit the while loop event though I have used the break statement. Whatever string I input to the first question, the program just repeats the same question.

I am using codeblocks. There are no errors with the program itself in the build log.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{

float a;
float p;
float r;
string cr;
string time;

while (1 == 1) {

cout << "Is your investing time best measured in days, weeks, months or years?" << endl;
cin >> time;

if(time != "days" || "weeks" || "months" || "years" || "Days" || "Weeks" || "Months" || "Years") {

cout << endl;
cout << "Answer invalid, please give a valid answer (e.g days)..." << endl;
cout << endl;
continue;

} else {

break;

}

}

cout << "Please enter the currency you are using: " << endl;
cin >> cr;

cout << "Please enter the amount of money being invested: " << endl;
cin >> p;

cout << "Please enter the interest rate in percent: " << endl;
cin >> r;
r = r / 100;

int numTime;

cout << "How many\n" << time << " will you be investing?" << endl;
cin >> numTime;

::cout << ::fixed;

for ( int pointlessTime = 1; pointlessTime <= numTime; pointlessTime++) {
a = p * pow(1+r, pointlessTime);
cout << "In " << pointlessTime << " " << time << " " << "you will have a total of " << a << " " << cr << endl;
}

return 0;
}
Last edited on
if(time != "days" || "weeks" || "months" || "years" || "Days" || "Weeks" || "Months" || "Years") {

This is a nasty part of C++. That syntax is legal but it doesn't do what you think it does. You need to write this as
if(time != "days" && time != "weeks" && time != "months" && time != "years" && time != "Days" && time != "Weeks" && time != "Months" && time != "Years") {

The way you did it gets parsed as:
if((time != "days") || "weeks" || "months" || "years" || "Days" || "Weeks" || "Months" || "Years") {
This means it compares time to "days". If they aren't equal then it evaluates "weeks". This expression is a pointer to a C string, since the pointer is non-null, the program considers it "true" and that makes the entire if expression true.
This line is wrong
if(time != "days" || "weeks" || "months" || "years" || "Days" || "Weeks" || "Months" || "Years")

should be
if(time != "days" && time != "weeks" && time != "months" && time != "years")

Please use code tags to format your code. That way, more people will answer your questions. And you should always use more descriptive names for your variables. So instead of 'cr' use 'currency' etc. Hope this helps :)
Last edited on
Thanks guys!
Topic archived. No new replies allowed.