I tried to write a code that asked me to input numbers one by one and when a certain char was inserted ( in this case 'x' ) it would stop the loop. But when I insert that char it starts spamming me with "Insert Number" . I think that the fault is that I'm trying to insert a char in an int array, but I can't think a way around it.
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
cin >> numbers[index];
h=(char)numbers[index];
index++;
}
while(h!='x');
This happens because 'x' is not a number and cin >> numbers[index]; operation fails, without consuming that data. So the loop continues, gets the same x, fails again and everything starts all over again. You can check for result of input operation, something like this:
#include <iostream>
using namespace std;
int main ()
{
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
if (cin >> numbers[index])
{
h=(char)numbers[index];
index++;
}
else
{
cout << "Hey, that was not a number! Bye." << endl;
break;
}
}
while(h!='x');
}
You should write a loop as:
while(cin >> numbers[index])
index++;
It will read all the integers, untill you enter some invalid input, be it 'x' or any other character. Now if you want to skip all invalid inputs and continue reading integers (which might be after invalid inputs), and want to consider only 'x' to exit from the loop, then wrap the above loop with another loop as:
char ch;
do
{
while(cin >> numbers[index])
index++;
cin.clear(); //clear the error flags, so you can use cin to continue reading
cin >> ch; //read the invalid character
} while(ch != 'x');
One piece of advice: prefer using std::vector<long int> over long int numbers[100]. What if user entered more than 100 integers, then your program will be corrupted.
Because you're trying to read in an integer, any character that isn't a digit can't be converted to a number and will jam up the input - you'll get an error and the bad character will not be removed from the stream. The next time you try to read you'll get the same error.
If you expect a number or a string, always read the input as a string, and try converting it to a number afterwards if the string isn't "x":
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main(int argc, char *argv[])
{
std::vector<long int> numbers;
std::string line;
while(std::getline(std::cin, line) && line != "x") {
std::istringstream input(line);
long int value;
// Check that there is only a number with nothing else after
if((input >> value) && input.get() == std::char_traits<char>::eof()) {
numbers.push_back(value);
} else {
std::cout << "Invalid Entry, please retry" << std::endl;
}
}
//...
return 0;
}
Related
I need help with the following snippet:
Using string in the following loop terminates:
int main() {
string in;
while(1){
cin >> in;
if (in == "|")
break;
}
But using int in the following loop does not terminates:
int main() {
int in;
while(1){
cin >> in;
if (in == '|')
break;
else
cout<< in << "\n";
}
I want to terminate the last shown snippet. Is it possible to do using int in.
I've seen the post C++ Terminate loop using a char input to int but no solution.
While characters are represented in the computer as small integers, an int is not the same as a char. Not in C++.
When you read into an int variable the >> operator tries to parse the input as an integer, as a number and not as a character.
If you want to read a character then read a character:
char in;
std::cin >> in;
If you try to read an integer, and the input is not a number, then the input operator will fail. See e.g. this very simple example.
This is the approach I used
I needed to input integers to a vector as input using while loop indefinitely and terminate it using a character.
This approach takes the input as character and then convert this char into integer.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
char in;
std::vector<int> vec;
while(1){
cin>>in;
if(in == '|'){
break;
}
vec.push_back(in - '0');
}
for(int j=0; j<vec.size(); j++){
cout<<vec[j];}
return 0;
}
I'm having a problem with what should be incredibly simple code. I want to take in an integer between 1 and 3 with error checking. It works fine for checking for numbers that are too large or too small, but when a alpha/number combination is entered, it gets stuck in an infinite loop. Suggestions?
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
int input;
cout << "\nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
cin >> input;
while(input< 1 || input> 3){
cout << "\n---------------------------------------" << endl;
cout << "\n[!] The number you entered was invalid." << endl;
cout << "\nPlease re-enter a number from 1 to 3" << endl;
cout << "-> ";
cin >> input;
}
cout << "You chose " << input << endl;
}
The problem is that:
cin >> input;
Will cause the bad bit to be set when you try and read a non numeric value. After that happens any attempt to use the operator>> is silently ignored.
So the way to correct for this is to test if the stream is in a good state and if not then reset the state flags and try and read again. But note that the bad input (that caused the problem) is still on the input so you need to make sure you throw it away as well.
if (cin >> input)
{
// It worked (input is now in a good state)
}
else
{
// input is in a bad state.
// So first clear the state.
cin.clear();
// Now you must get rid of the bad input.
// Personally I would just ignore the rest of the line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// now that you have reset the stream you can go back and try and read again.
}
To prevent it getting stuck (which is caused by the bad bit being set) read into a string then use a string stream to parse user input. I also prefer this method (for user interactive input) as it allows for easier combination of different styles of reading (ie combining operator>> and std::getline() as you can use these on the stringstream).
#include <iostream>
#include <sstream>
#include <string>
// using namespace std;
// Try to stop using this.
// For anything other than a toy program it becomes a problem.
int main(int argc, char *argv[])
{
int input;
std::string line;
while(std::getline(std::cin, line)) // read a line at a time for parsing.
{
std::stringstream linestream(line);
if (!(linestream >> input))
{
// input was not a number
// Error message and try again
continue;
}
if ((input < 1) || (input > 3))
{
// Error out of range
// Message and try again
continue;
}
char errorTest;
if (linestream >> errorTest)
{
// There was extra stuff on the same line.
// ie sobody typed 2x<enter>
// Error Message;
continue;
}
// it worked perfectly.
// The value is now in input.
// So break out of the loop.
break;
}
}
#include <iostream>
#include <string>
using namespace std;
int validatedInput(int min = 1, int max = 3)
{
while(true)
{
cout << "Enter a number: ";
string s;
getline(cin,s);
char *endp = 0;
int ret = strtol(s.c_str(),&endp,10);
if(endp!=s.c_str() && !*endp && ret >= min && ret <= max)
return ret;
cout << "Invalid input. Allowed range: " << min << "-" << max <<endl;
}
}
int main(int argc, char *argv[])
{
int val = validatedInput();
cout << "You entered " << val <<endl;
return 0;
}
Most of these answers include unnecessary complexity.
Input validation is a perfect time to use a do-while
do{
cout << "\nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}while(!(cin >> input))
Use numeric_limits<streamsize>::max() to completely clear the
buffer after a failed cin.
Use cin.clear() to reset the fail flag on cin so !cin wont
always evaluate false.
cin.fail() is fine. However some would consider !cin more natural.
from my previous post https://stackoverflow.com/a/43421325/5890809
You declared input as int but when you write an alphanumeric character to input it will try to implicitly convert it into integer. But you error checking does not account for this.
Ur problem can be easily solved by changing your while loop. instead of checking this how about you check
while(input!=1 || input!=2 || input!=3)
Hey guys so I'm writing a program where I can only in one letter(ex. a,b,c) and I want the program to exit if the user tries to enter anything else ex)string int etc. The code sample I have so far is this. When I try to run this it the program will always say that the input is a letter.
#include <iostream>
using namespace std;
int main(){
char guess;
bool isnotletter
cout<<"Enter your guess"<<endl;
cin>>guess;
isnotletter=cin.fail();//cin.fail returns true if the input is something that disagrees with the data type (ex string and int would)
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(isnotletter==true)
{
cout<<"Error"<<endl;
exit(1);
}
else
cout<<"You are a letter"<<endl;
}
A simple way to do this, including flushing the line in case of bad input, would be to read the whole line and see if it consisted of a single character:
std::string s;
if ( !getline( cin, s ) ) // reads a whole line
cout << "Error or end-of-file\n";
else if ( s.size() != 1 )
cout << "Input was not a single character\n";
else if ( !isalpha(s[0], locale()) )
cout << "Input was not a letter\n";
else
cout<<"You are a letter"<<endl;
Of course, you could combine some of those error conditions if you are not interested in specific error messages.
I think isalpha() function helps you.
Source
#include <iostream>
#include <ctype.h>
#include <string.h>
using namespace std;
int main(){
string guess;
cout<<"Enter your guess"<<endl;
cin>>guess;
if( (!isalpha(guess[0])) || (guess.size() > 1) )
{
cout<<"Error"<<endl;
return -1;
}
else
cout<<"You are a letter"<<endl;
return 0;
}
cin.fail() will return true if there is an exception thrown when assigning a value, that much is correct. However, using cin to receive a string and assign it to a character doesn't throw an exception, as what happens is that cin simply takes the first character in the input buffer and assigns it to guess, leaving the rest of the string in queue within the input buffer. This is considered acceptable by cin.
In your code, if the user had written "hello", guesswill have the character h. If you use another cin below, and assign it to let's say char mychar, it won't ask the user again, as there is still input waiting. Instead, it'll assign the next character e to mychar.
Example:
#include <iostream>
using namespace std;
int main(){
char guess;
char mychar;
bool isnotletter;
cout<<"Enter your guess"<<endl;
cin>>guess;
isnotletter=cin.fail();
//cin.fail returns true if the input is something that disagrees with the data type (ex string and int would)
cin>>mychar;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(isnotletter==true)
{
cout<<"Error"<<endl;
exit(1);
}
else
cout<<"You are a letter"<<endl;
system("pause");
return 0;
}
The second char mychar will receive the second character in the first string input, without asking for the user to input again.
A solution could be using a string to get all the inputs, and if you want then you can assign the first letter of the string to your char. Later, you can use if and measure the string size, and if it is >1 then output the Error message.
#include <iostream>
#include <string>
using namespace std;
int main(){
string myString;
char mychar;
cout<<"Enter your guess"<<endl;
cin >> myString;
mychar = myString[0];
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(myString.size() > 1)
{
cout<<"Error"<<endl;
//exit(1);
}
//Code to check for numbers
else if(string::npos != myString.find_first_of("0123456789"))
{
cout << "digit(s)found!" << std::endl;
}
else
cout<<"You are a letter"<<endl;
system("pause");
return 0;
}
For text validation, regex is quiet of a powerful tool in general (can be slow though).
regex charRegex("(\\+|-)?[[:alpha:]]+");
string input;
cout<<"Input : "<<endl;
cin>>input;
if(!regex_match(input,charRegex))
cout<<"Invalid input"<<endl;
Companion of every regex fanatic.
I currently am using a function I found in another StackOverflow post(I can't find it), that I am using before, named "GetInt". My issue with it is that if the user inputs something like "2 2 2" it puts it into my next two Cin's. I have tried getLine, but it requires a string and I am looking for an int value. How would I structure a check to sanitize for an integer value greater than 2 and throw an error to the 2 2 2 answer.
#include <iostream>
#include <string>
#include <sstream>
#include "Board.cpp"
#include "Player.cpp"
using namespace std;
int getInt()
{
int x = 0;
while (!( cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please input a proper 'whole' number: " << endl;
}
return (x);
}
and my call
do
{
//do
//{
cout << "How many players are there? \n";
numberOfPlayers = getInt();
//} while (isdigit(numberOfPlayers) == false);
} while (numberOfPlayers < 2);
EDIT:
I chose Justin's answer because it was the closest to my original code and solved the issue without major changes.
Integers are delimited by spaces and the input 2 2 2 is just multiple integers. If you want to make sure that just one integer is entered per line you could skip whitespace characters until a newline is found. If a non-whitespace is found prior to a newline you could issue an error:
numberOfPlayers = getInt();
int c;
while (std::isspace(c = std::cin.peek()) && c != '\n') {
std::cin.ignore();
}
if (c != std::char_traits<char>::eof() && c != '\n') {
// deal with additional input on the same line here
}
You were on the right track with std::getline. You read the whole line as a string, then put it into a std::istringstream and read the integer out.
std::string line;
if( std::getline(cin, line) ) {
std::istringstream iss(line);
int x;
if( iss >> x ) return x;
}
// Error
This will have the effect of discarding any fluff that comes after the integer. It will only error if there is no input or no integer could be read.
If you want to have an error when stuff appears after the integer, you could take advantage of the way strings are read from a stream. Any whitespace is okay, but anything else is an error:
std::istringstream iss(line);
int x;
if( iss >> x ) {
std::string fluff;
if( iss >> fluff ) {
// Error
} else {
return x;
}
}
Change your code to this:
int getInt()
{
int x = 0;
while (!( cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please input a proper 'whole' number: " << endl;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return (x);
}
Your code to ignore the rest of the line after receiving the integer is only called if the integer collection fails (for example, you type "h" as the number of players).
I'm writing a program that prompts the user for:
Size of array
Values to be put into the array
First part is fine, I create a dynamically allocated array (required) and make it the size the user wants.
I'm stuck on the next part. The user is expected to enter in a series of ints separated by commas such as: 1,2,3,4,5
How do I take in those ints and put them into my dynamically allocated array? I read that by default cin takes in integers separated by whitespace, can I change this to commas?
Please explain in the simplest manner possible, I am a beginner to programming (sorry!)
EDIT: TY so much for all the answers. Problem is we haven't covered vectors...is there a method only using the dynamically allocated array I have?
so far my function looks like this. I made a default array in main. I plan to pass it to this function, make the new array, fill it, and update the pointer to point to the new array.
int *fill (int *&array, int *limit) {
cout << "What is the desired array size?: ";
while ( !(cin >> *limit) || *limit < 0 ) {
cout << " Invalid entry. Please enter a positive integer: ";
cin.clear();
cin.ignore (1000, 10);
}
int *newarr;
newarr = new int[*limit]
//I'm stuck here
}
All of the existing answers are excellent, but all are specific to your particular task. Ergo, I wrote a general touch of code that allows input of comma separated values in a standard way:
template<class T, char sep=','>
struct comma_sep { //type used for temporary input
T t; //where data is temporarily read to
operator const T&() const {return t;} //acts like an int in most cases
};
template<class T, char sep>
std::istream& operator>>(std::istream& in, comma_sep<T,sep>& t)
{
if (!(in >> t.t)) //if we failed to read the int
return in; //return failure state
if (in.peek()==sep) //if next character is a comma
in.ignore(); //extract it from the stream and we're done
else //if the next character is anything else
in.clear(); //clear the EOF state, read was successful
return in; //return
}
Sample usage http://coliru.stacked-crooked.com/a/a345232cd5381bd2:
typedef std::istream_iterator<comma_sep<int>> istrit; //iterators from the stream
std::vector<int> vec{istrit(in), istrit()}; //construct the vector from two iterators
Since you're a beginner, this code might be too much for you now, but I figured I'd post this for completeness.
A priori, you should want to check that the comma is there, and
declare an error if it's not. For this reason, I'd handle the
first number separately:
std::vector<int> dest;
int value;
std::cin >> value;
if ( std::cin ) {
dest.push_back( value );
char separator;
while ( std::cin >> separator >> value && separator == ',' ) {
dest.push_back( value );
}
}
if ( !std::cin.eof() ) {
std::cerr << "format error in input" << std::endl;
}
Note that you don't have to ask for the size first. The array
(std::vector) will automatically extend itself as much as
needed, provided the memory is available.
Finally: in a real life example, you'd probably want to read
line by line, in order to output a line number in case of
a format error, and to recover from such an error and continue.
This is a bit more complicated, especially if you want to be
able to accept the separator before or after the newline
character.
You can use getline() method as below:
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::string input_str;
std::vector<int> vect;
std::getline( std::cin, input_str );
std::stringstream ss(str);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
}
The code is taken and processed from this answer.
Victor's answer works but does more than is necessary. You can just directly call ignore() on cin to skip the commas in the input stream.
What this code does is read in an integer for the size of the input array, reserve space in a vector of ints for that number of elements, then loop up to the number of elements specified alternately reading an integer from standard input and skipping separating commas (the call to cin.ignore()). Once it has read the requested number of elements, it prints them out and exits.
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
using namespace std;
int main() {
vector<int> vals;
int i;
cin >> i;
vals.reserve(i);
for (size_t j = 0; j != vals.capacity(); ++j) {
cin >> i;
vals.push_back(i);
cin.ignore(numeric_limits<streamsize>::max(), ',');
}
copy(begin(vals), end(vals), ostream_iterator<int>(cout, ", "));
cout << endl;
}
#include <iostream>
using namespace std;
int main() {
int x,i=0;
char y; //to store commas
int arr[50];
while(!cin.eof()){
cin>>x>>y;
arr[i]=x;
i++;
}
for(int j=0;j<i;j++)
cout<<arr[j]; //array contains only the integer part
return 0;
}
The code can be simplified a bit with new std::stoi function in C+11. It takes care of spaces in the input when converting and throws an exception only when a particular token has started with non-numeric character. This code will thus accept input
" 12de, 32, 34 45, 45 , 23xp,"
easily but reject
" de12, 32, 34 45, 45 , 23xp,"
One problem is still there as you can see that in first case it will display " 12, 32, 34, 45, 23, " at the end where it has truncated "34 45" to 34. A special case may be added to handle this as error or ignore white space in the middle of token.
wchar_t in;
std::wstring seq;
std::vector<int> input;
std::wcout << L"Enter values : ";
while (std::wcin >> std::noskipws >> in)
{
if (L'\n' == in || (L',' == in))
{
if (!seq.empty()){
try{
input.push_back(std::stoi(seq));
}catch (std::exception e){
std::wcout << L"Bad input" << std::endl;
}
seq.clear();
}
if (L'\n' == in) break;
else continue;
}
seq.push_back(in);
}
std::wcout << L"Values entered : ";
std::copy(begin(input), end(input), std::ostream_iterator<int, wchar_t>(std::wcout, L", "));
std::cout << std::endl;
#include<bits/stdc++.h>
using namespace std;
int a[1000];
int main(){
string s;
cin>>s;
int i=0;
istringstream d(s);
string b;
while(getline(d,b,',')){
a[i]= stoi(b);
i++;
}
for(int j=0;j<i;j++){
cout<<a[j]<<" ";
}
}
This code works nicely for C++ 11 onwards, its simple and i have used stringstreams and the getline and stoi functions
You can use scanf instead of cin and put comma beside data type symbol
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[10],sum=0;
cout<<"enter five numbers";
for(int i=0;i<3;i++){
scanf("%d,",&a[i]);
sum=sum+a[i];
}
cout<<sum;
}
First, take the input as a string, then parse the string and store it in a vector, you will get your integers.
vector<int> v;
string str;
cin >> str;
stringstream ss(str);
for(int i;ss>>i;){
v.push_back(i);
if(ss.peek() == ','){
ss.ignore();
}
}
for(auto &i:v){
cout << i << " ";
}