John2010 John2010 - 22 days ago 7
C++ Question

Unable to properly do a While Loop

I am trying to do a while loop. I have been trying for a long time, but still cannot figure this out.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
char input;
double voltage, current;

while ((input = 'Y'))
cout << "Enter the voltage: ";
cin >> voltage;
cout << "Enter the current: ";
cin >> current;

cout << "The resistance is " << voltage/current << endl;

cout << "Do you wish to continue? [Y/N]";
cin >> input;

Entering other variables other than 'Y' still causes the code to loop. Doing //while ((input == 'Y')) does not give me an output


You problem is that the first time you enter the loop, input has no value. This can be fixed by giving it an initial value in its declaration

int main()
char input = 'Y';
double voltage, current;

while (input == 'Y')

You then still have the problem that the user might enter 'y' instead of 'Y' at the end of the loop. We'll leave that as an exercise for the student.