I'm learning C++, so I don't fully understand what's going on with my code here, but from what I've been able to glean, it seems like it could be some kind of buffer issue.
#include <stdio.h>
#include <vector>
#include <iostream>
#include <typeinfo>
using namespace std;
bool stopRun = true;
int height, average, total, count;
vector <int> heights;
int main ()
{
while (stopRun)
{
cout << "Enter a height, or 'end' to quit: ";
cin >> height;
if (typeid(height).name() == "i")
{
heights.push_back(height);
cout << heights[0];
count++;
}
else if (typeid(height).name() == "i")
{
cout << "\nPlease enter an integer: ";
continue;
}
if (count == 5)
{
stopRun = false;
}
}
for (int i = 0; i < heights.size(); i++)
{
total += heights[i];
cout << "\nTotal: " << total;
}
return 0;
}
For some reason, this code will continuously output: "Enter a height, or 'end' to quit: ". In an earlier version, it would output: "Enter a height, or 'end' to quit: Please enter an integer: ".
What I think is going on is that my "cin >> height;" line is pulling in the output from "Please enter an integer: " and treating it as my input, which identifies it as not being of type integer, which starts the infinite loop.
How do I clear the input buffer so that it doesn't bring in cout statements? Or is that even the issue I'm experiencing here?
Thanks in advance!
I suggest to catch the string. If string is not "end" then convert to number inside try/catch
you can use this function at the start of your program fflush(stdin). It will clear your input buffer.
You are attempting to read an int and a string in the same line of code. I suggest you use getline() to read the input and try to convert the string to int.
std::string input;
while (heights.size() != 5) {
cout << "Enter a height, or 'end' to quit: ";
if (std::getline(cin, input)) {
if (input == "end") break;
try {
heights.push_back(std::stoi(input));
}
catch (std::invalid_argument e) {
cout << "\nPlease enter an integer: ";
}
}
}
if (string(typeid(height).name()) == "i")
What you had wrong was the comparison of a pointer and string. Since typeid(height).name() returns a pointer to a c-string with the name for the object.
Related
I'm trying to get two space-separated variables and running into this error, as well as [no operator ">>" matches these operands] and [syntax error: ">>"].
#include <iostream>
#include <string>
#include <vector>
using namespace std;
...
void player(char array[][ROWS_AND_COLUMNS], char letter)
{
bool element_occupied = false;
do
{
int row = 0;
int column = 0;
cout << "Enter player " << letter << ", row and column:";
cin >> inputValidate(row, 1, 3) >> inputValidate(column, 1, 3);
if (array[(row - 1)][(column - 1)] == '*')
{
array[(row - 1)][(column - 1)] = letter;
element_occupied = true;
}
else
{
cout << "Sorry, that spot is taken." << endl;
element_occupied = false;
}
} while (element_occupied == false);
}
inputValidate() takes the input, minimum value, and maximum value, and returns the input value if it is 1, 2, or 3.
EDIT:
int inputValidate(int user_number, int lowest, int highest)
{
while (!(cin >> user_number) || (user_number < lowest || user_number > highest))
{
cout << "Error. Enter a number from " << lowest << " to " << highest << ": ";
cin.clear();
}
return user_number;
}
This is a tic-tac-toe game.
inputValidate() returns a temporary int, an rvalue, which operator>> can't read into. It expects an lvalue instead (ie, a variable with a name). That is why you are getting errors on the cin >> inputValidate(...) statement.
Even if the statement could compile, it simply doesn't make sense to use. inputValidate() does its own reading of cin, so player() shouldn't be trying to pass the return value of inputValidate() to cin >> to begin with. inputValidate() would read in a validated number and return it, then player would be trying to read in a new unvalidated number to overwrite it.
For that matter, there is no point in passing in the user_number parameter at all. You are passing it in by value, just to immediately overwrite it with user input. So the value passed in by player() is irrelevant. If you want to return the user's input then user_number should be a local variable inside of inputValidate(). Otherwise, it should be an output parameter passed by reference instead, and inputValidate()'s return value should be void.
Also, when operator>> fails inside of inputValidate() due to invalid input, you are not discarding the input that caused it to fail. cin.clear() only resets the stream's error state, it does not discard any data. You need to call cin.ignore() for that.
With that said, try something more like this:
#include <iostream>
#include <string>
#include <vector>
#include <limits>
using namespace std;
...
int inputValidate(int lowest, int highest)
{
int user_number;
do
{
if (!(cin >> user_number))
{
cout << "Invalid. Enter a valid number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (user_number < lowest || user_number > highest)
{
cout << "Error. Enter a number from " << lowest << " to " << highest << ": ";
}
else break;
}
while (true);
return user_number;
}
void player(char array[][ROWS_AND_COLUMNS], char letter)
{
int row, column;
do
{
cout << "Enter player " << letter << ", row and column:";
row = inputValidate(1, 3) - 1;
column = inputValidate(1, 3) - 1;
if (array[row][column] == '*')
break;
cout << "Sorry, that spot is taken." << endl;
}
while (true);
array[row][column] = letter;
}
I have the following bit of code that I'm using to check whether an input is a multiple of 3, 5 or Both. If the user does not enter a number I would like it to print the value stored in UserInput. At the moment it is just returning 0, any suggestions would be much appreciated!
#include <iostream>
using namespace std;
int main()
{
int UserInput;
cout << "Please enter a number:";
cin >> UserInput;
if (!cin) {
cout << UserInput;
}
else if ((UserInput%3 == 0) && (UserInput%5 == 0)) {
cout << "FizzBuzz";
}
else if (UserInput%3 == 0) {
cout << "Fizz";
}
else if (UserInput%5 == 0) {
cout << "Buzz";
}
}
If the user input cannot be read into an int, cin is placed in a fail state and nothing is read. The contents of UserInput are useless to you. You will have to take cin out of the error state with clear and read the stream into something guaranteed to be able to hold the user's input like a std::string.
if (std::cin >> UserInput) // Get input and make sure input was read check for good input
{
// do the fizbuzz thing.
}
else
{
std::cin.clear(); // remove the error flags set by reading a non-number
std::string badinput;
getline(std::cin, badinput); // read the bad input.
std::cout << "User input: " << badinput << std::endl; // write the bad input
}
I'm trying to make a loop to check input strings for numbers only, and negative numbers are allowed. I'm new to programming, this is for a class project.
This code works, to an extent. When it shows the output, it does not show the first number, and does not allow - to be used. I cannot figure out where I'm going wrong in this.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string userInput;
int i = 0;
bool checkInput(int);
int main()
{
do
{
cout << "Please enter a numeric value : ";
string userInput;
cin >> userInput[i];
}
while (!checkInput(userInput[i]));
system("pause");
return 0;
}
bool checkInput(int input)
{
string userInput;
int i;
cin >> userInput;
for (int i = 0; i < userInput.length(); i++)
if (isdigit(userInput[i]))
{
cout << "\nYour input " << userInput << " is a valid numeric input." << endl;
return true;
}
else
{
cout << "Please enter a valid numeric value: ";
cin >> userInput[i];
return false;
}
}
Your code doesn't work because you are not utilizing std::string correctly.
When main() prompts the user, it reads into a char of an empty std::string, which is undefined behavior. You should be reading into the std::string itself without calling its operator[] at all. operator>> has an overload for reading std::string values.
checkInput() is just all kinds of wrong. It takes an int as input instead of a std::string, but ignores that input and waits for the user to type in another string value. Then it loops through that string instead of the one read by main(), and only checks the 1st char before exiting. If the char is a digit, checkInput() returns true, and main() exits. Otherwise, checkInput() prompts the user to type in yet another char and then returns false, which then causes main() to prompt the user to type in yet another char. checkInput() does not actually loop through an entire string at all, and does no have any handling for the - character.
Try this instead:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>
#include <limits>
using namespace std;
bool checkInput(const string &);
int main()
{
string userInput;
cout << "Please enter a numeric value : ";
do
{
cin >> userInput;
if (checkInput(userInput))
break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter a valid numeric value: ";
}
while (true);
cout << "\nYour input " << userInput << " is a valid numeric input." << endl;
system("pause");
return 0;
}
bool checkInput(const string &input)
{
if (input.empty())
return false;
string::size_type i = 0;
if (input[0] == '-')
{
++i;
if (i == input.length())
return false;
}
do
{
if (!isdigit(input[i]))
return false;
}
while (++i < input.length());
return true;
}
However, the best way to handle this situation is to simply not allow the user to enter non-integer values to begin with. operator>> has overloads for reading integer values, both signed and unsigned types. In this case, reading int values will suffice. Let cin do all of the input validation for you:
#include "stdafx.h"
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int userInput;
cout << "Please enter a numeric value : ";
while (!(cin >> userInput))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please enter a valid numeric value: ";
}
cout << "\nYour input " << userInput << " is a valid numeric input." << endl;
system("pause");
return 0;
}
I have this snippets of code from my original long program, and as much as it looks simple, it doesn't work correctly! I am brand-new to c++ language, but I know in Java that would be the way to do it (Regardless of the syntax).
Simply put, this should ask the user for an input to answer the following multiplication (5*5), however, it should also check if the user entered a wrong input (not number), keep asking the user again and again... Somehow, it keeps running forever without taking a new input!!
I hope to get, not only an answer, but also a reason for such an error!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
Well you need to clear the error state before accepting new input. Call cin.clear() then cin.ignore() before trying to read input again.
I would do something like.
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
First, cin.fail() is not going to adequately check if your answer is a natural number or not with the type set to int (could also be negative).
Second, your boolean isValidAnswer is really checking if it's is an invalid answer.
Third (and most importantly), as another answer suggests, you should put in cin.clear() to clear the failure state, and then followed by cin.ignore(), which will remove the failed string from cin.
Fourth, cin will only check if an int exists somewhere in the string. You'll need to perform your own string comparison to determine if the entire input is a int (see answer below, based on this answer).
Updated:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:\n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:\n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!\n";
return 0;
}
is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}