I'm trying to display "invalid option" when the user enters a letter instead of a number. I tried using the isalpha() function but I get an infinite loop showing 0 Invalid option!try again:. The 0 from the output is displayed when entering a letter. When I actually type in the number 0 the message is displayed and the loop is exited.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
cout << "Guess a number 1-100: ";
cin >> userInput;
cout << endl;
if(userInput == answer) {
cout << "Correct!\n\n";
}
while(userInput != answer) {
if(userInput < 1 || userInput > 100 || isalpha(userInput)) {
cout << userInput << " Invalid option!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
cin >> userInput;
cout << endl;
}
}
cout << userInput << " is correct!\n\n";
return 0;
}
When you need to deal with user input differently based on some logic, your best option is to:
Read lines of text. Figure out what to do when there is no more input.
Process each line of text using custom logic.
In your case, you could use:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
std::string line;
cout << "Guess a number 1-100: ";
while ( getline(std:::cout, line ) )
{
// Deal with empty lines.
if ( line.size() == 0 )
{
continue;
}
// If the first character is a letter ...
if(isalpha(line[0])) {
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
// Extract the number from the line using a stringstream.
// If there is a problem extracting the number ...
std::istringstream str(line);
if ( !(str >> userInput ) )
{
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
cout << endl;
// Check the user input against the random answer.
if(userInput == answer) {
cout << "Correct!\n\n";
}
else if(userInput < 1 || userInput > 100 ) {
cout << userInput << " Invalid option!\ntry again: ";
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
}
cout << "Guess a number 1-100: ";
}
cout << userInput << " is correct!\n\n";
return 0;
}
Related
I am trying to write a program that counts how many times a specific number is inputted by a user from a while loop. Here is the idea:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
bool progLoop = true;
int Number;
char response;
while (progLoop == true)
{
cout << "Please enter a number: " << endl; \
cin >> Number;
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << endl; //IDK how to do this part which is what I'm looking for.
cout << "Do you want to enter another number?" << endl;
cin >> response;
if (response == 'y')
{
progLoop == true;
}
else if(response == 'n')
{
progLoop == false;
}
}
}
I'm looking for a way that I can store a sort of value of how many times that specific number has been entered into the program. Would like to clarify if there are any questions! Thanks! (Modifying my code would be great!)
Use a hashmap:
#include <unordered_map>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int number;
char response = 'y';
unordered_map<int, int> m; // your hashmap
while (response == 'y')
{
cout << "Please enter a number: " << endl;
cin >> number;
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << ++m[number] << endl; // preincrement your hashmap at key number
cout << "Do you want to enter another number? (y/n)" << endl;
cin >> response;
response = tolower(response); // give a chance to exit the loop if your user like to use caplock (like Trump)
}
}
Expanding my comment into an answer
One way of doing this is to use an std::vector and every time a new number is inputted, it is pushed back into the vector. Then you can std::count that number when you need to check. In your program, it would look something like this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
int main() {
bool progLoop = true;
int Number;
std::vector<int> numCount;
char response;
while (progLoop == true)
{
cout << "Please enter a number: " << endl;
cin >> Number;
numCount.push_back(Number);
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << std::count(numCount.begin(), numCount.end(), Number) << endl;
cout << "Do you want to enter another number?" << endl;
cin >> response;
if (response == 'y')
{
progLoop = true; // You accidentally used == here
}
else if(response == 'n')
{
progLoop = false; // You accidentally used == here
}
}
}
I have created a Prompt User to Loop to restart the program however when I type anything including "y" it just goes prompts me with "Press any key to continue . . . " and then closes. Here's my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int Multiple1 = 0;
int Multiple2 = 0;
char again = 'Y';
while (again == 'y' || again == 'Y')
{
int Multiple1 = 0;
int Multiple2 = 0;
cout << "Input your first Multiple: " << endl;
cin >> Multiple1;
cout << "Your First Multiple is: " << Multiple1 << endl;
cout << "Input your second Multiple: " << endl;
cin >> Multiple2;
cout << "Your Second Multiple is: " << Multiple2 << endl;
for (int i = 1; i <= 100; i++)
{
if (i % Multiple1 == 0 && i % Multiple2 == 0)
cout << "FizzBuzz" << endl;
else
if (i % Multiple1 == 0)
cout << "Fizz" << endl;
else
if (i % Multiple2 == 0)
cout << "Buzz" << endl;
else cout << i << endl;
}
{
cout << "Restart? (y/n) ";
cin >> again;
}
system("pause");
return 0;
}
}
Thank you.
This is my first project and I am completely new to coding so I am not sure what to do.
Your return 0 is misplaced, it should be outside the while loop.
And you shouldn't put a bracket {} around your cin >> again.
{ // this bracket doesn't needed
cout << "Restart? (y/n) ";
cin >> again;
}
Just use bracket when it needed e.g. in for, if, function, etc. It will not make a compile error. But I think it makes you misread and think the while loop was closed.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int Multiple1 = 0;
int Multiple2 = 0;
char again = 'Y';
while (again == 'y' || again == 'Y')
{
int Multiple1 = 0;
int Multiple2 = 0;
cout << "Input your first Multiple: " << endl;
cin >> Multiple1;
cout << "Your First Multiple is: " << Multiple1 << endl;
cout << "Input your second Multiple: " << endl;
cin >> Multiple2;
cout << "Your Second Multiple is: " << Multiple2 << endl;
for (int i = 1; i <= 100; i++)
{
if (i % Multiple1 == 0 && i % Multiple2 == 0)
cout << "FizzBuzz" << endl;
else
if (i % Multiple1 == 0)
cout << "Fizz" << endl;
else
if (i % Multiple2 == 0)
cout << "Buzz" << endl;
else cout << i << endl;
}
{ //This bracket doesn't need.
cout << "Restart? (y/n) ";
cin >> again;
continue;
} // This bracket doesn't need.
system("pause");
return 0;
}
}
I'm a very beginner in C++ and I'm actually following the Google tutorial.
Trying to go a little further with the second example, here is my problematic : checking if the input is a number and, if not, being able to restate it in the error message.
Here is a way I used to solve that but the code length tells me that there is a shorter way :
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool IsInteger(string str) {
size_t non_num_position = str.find_first_not_of("0123456789-");
size_t sign_position = str.find_first_of("-", 1);
if (non_num_position == string::npos && sign_position == string::npos) {
return true;
}
return false;
}
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
if (!IsInteger(input_string)) {
int input_string_length = input_string.size();
cout << "Sorry but « " << input_string << " » is not a number." << endl;
cin.clear();
cin.ignore(input_string_length, '\n');
continue;
}
input_number = atoi(input_string.c_str());
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
Here is the shorter way I try to follow but cin seems to be "emptied" once assigned to input_number (because of the bitwise operator ?) :
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
if (!(cin >> input_number)) {
getline(cin, input_string);
cout << "Sorry but " << input_string << " is not a number." << endl;
cin.clear();
cin.ignore(100, '\n');
continue;
}
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
SOLUTION :
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
try {
input_number = stoi(input_string);
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
}
catch (const exception&) {
cout << "Sorry but " << input_string << " is not a number." << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
The problem with your first attempt is that IsInteger is unnecessarily complicated and long. Otherwise, you had the right idea. Your second attempt is much less correct.... once you read from cin, the data is gone. So, as in the first attempt, you need to store the data in a string.
Here's an example which is a little shorter and doesn't need IsInteger at all:
size_t p = 0;
int input_number = std::stoi(input_string, &p);
if (p < input_string.length())
{
cout << "Sorry but " << input_string << " is not a number." << endl;
conitnue;
}
stoi's second argument tells you where the conversion to integer stopped working. So if there was non-int data in the string (such as '123abc') then p will be somewhere before the end of the string. If p is at the end, then the whole string must have been a number.
I have a program to write: write a program where user enters numbers until he enters 'e' or 'E'. All number entered by user sum and write on console.
So far, I write these, but I don't know how to break the loop when 'e' or 'E' is enter!? So, if anyone can help me with this.
#include<iostream>
using namespace std;
void main()
{
int sum=0, number=0;
do
{
cout << "Enter a number: \n";
cin >> number;
sum+=number;
} while (don't know what to type here);
cout << "Sum = " << sum << endl;
}
So try this piece of code please.
#include<iostream>
using namespace std;
int main()
{
int sum = 0, number = 0;
while (true)
{
cout << "Enter a number: \n";
if (cin >> number) sum += number;
else break;
}
cin.clear(); //reset the state of cin
char ch;
cin >> ch;
if (!(ch == 'e' || ch == 'E'))
{
cout << "Invalid input!" << endl;
system("pause");
return 0;
}
cout << "Sum = " << sum << endl;
}
you should make your program accept string as input, then try to convert that string to integer.
#include<iostream>
using namespace std;
int main() {
int sum = 0;
string number;
while (true){
cout << "Enter a number: ";
cin >> number;
if (number.length() == 1 && (number.at(0) == 'E' || number.at(0) == 'e')) break;
const char* data = number.c_str();
char* end = (char*)data + number.length();
int value = strtol(data, &end, 10);
sum += value;
};
cout << "Sum = " << sum << endl;
return 0;
}
Hi here is my question.
Write a program that uses a do-while statement. It reads in an integer
n from the keyboard. If n is not in the range 1 to 10 it makes an audible
“beep” and asks for another integer. If n is in the correct range, it writes
out “You have input n” and then exits.
Here is my answer.
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
do
{
cout << "Enter an integer." << endl;
cin >> number;
if (!(number >= 1 && number <= 10))
{
Beep(400, 400);
}
}
while (!(number >= 1 && number <= 10));
cout << "You have input " << number << endl;
system("PAUSE");
}
You can see the line
(!(number >= 1 && number <= 10))
is repeated. Is there any workaround for this?
int GetNumber()
{
int number;
cout << "Enter an integer." << endl;
cin >> number;
return number;
}
void main()
{
int n = GetNumber();
while(n < 1 || n > 10)
{
Beep(400, 400);
n = GetNumber();
}
cout << "You have input " << n << endl;
system("PAUSE");
}
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
bool invalid_input = true;
do
{
cout << "Enter an integer." << endl;
cin >> number;
invalid_input = !(number >= 1 && number <= 10);
if (invalid_input)
{
Beep(400, 400);
}
}
while (invalid_input);
cout << "You have input " << number << endl;
system("PAUSE");
}
Perhaps...
int number = 0;
while (true)
{
cout << "Enter an integer." << endl;
if (cin >> number && number >= 1 && number <= 10)
break;
Beep(400, 400);
}
cout << "You have input " << number << endl;
system("PAUSE");