#include <iostream>
int main (void)
{
usingnamespace std;
int firstDigit;
int secondDigit;
int thirdDigit;
int number;
int sum;
int remainder;
char ans;
do {
cout << "Enter a three-digit number: ";
cin >> number;
firstDigit=number/100;
remainder=number%100;
secondDigit=remainder/10;
remainder=number%10;
thirdDigit=remainder;
cout << "The first digit is " << firstDigit << endl;
cout << "The second digit is " << secondDigit << endl;
cout << "The third digit is " << thirdDigit << endl;
sum=firstDigit+secondDigit+thirdDigit;
cout << "The sum of the digits is " << sum << endl;
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N'.\n";
cin >> ans;
} while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
system("pause");
return(0);
}
The actual code works fine. You input a 3 digit # like 353 and it shows 3,5, and 3 on separate lines, and then adds them to get 11.
The problem arises with the do while loop at the end of the program. I'm trying to ask the user if they want to run the program - yes or no. It SHOULD loop the program if you type Y (capital) or y (lowercase), but instead, asks "Press any key to continue" and then closes. If you type N (capital) or n (lowercase), you get the same result, but in the case, it's working (in a way.)
I'm not getting any errors or warnings, since I'm able to compile and run the program.
Your condition is "while ans isn't Y, N, y or n". So your loop will break when the user enters one of those values. Essentially you're doing the opposite of what you want. It would be simpler to change the condition to "true": while (true); and then to have an if block:
1 2 3 4
if (ans == 'Y' || ans == 'y')
continue;
elsebreak;
Also don't use system(). Use std::cin.get(); instead.
#include <iostream>
int main (void)
{
usingnamespace std;
int firstDigit;
int secondDigit;
int thirdDigit;
int number;
int sum;
int remainder;
char ans;
do {
cout << "Enter a three-digit number: ";
cin >> number;
firstDigit=number/100;
remainder=number%100;
secondDigit=remainder/10;
remainder=number%10;
thirdDigit=remainder;
cout << "The first digit is " << firstDigit << endl;
cout << "The second digit is " << secondDigit << endl;
cout << "The third digit is " << thirdDigit << endl;
sum=firstDigit+secondDigit+thirdDigit;
cout << "The sum of the digits is " << sum << endl;
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N'.\n";
cin >> ans;
while(true);
if (ans== 'Y' || ans=='y')
continue;
elsebreak;
}
system("pause");
return(0);
}
I don't know what/where to put std::cin.get(); and what to even put in between the parantheses.
Also, I get these errors when I try to compile:
E:\C++ Programming\Exercise 10, Page 3-24.cpp In function `int main()':
41 E:\C++ Programming\Exercise 10, Page 3-24.cpp expected `while' before "system"
41 E:\C++ Programming\Exercise 10, Page 3-24.cpp expected `(' before "system"
41 E:\C++ Programming\Exercise 10, Page 3-24.cpp expected `)' before ';' token