I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7. I have been able to make that part of my code work successfully. However, the next part consists of asking the user to enter a specific letter, in this case 'c'. If they do not enter 'c' then the loop should ask them to input another character. Whenever I run this code, it is creating an infinite loop whether I enter 'c' or another letter. I think my expression in my second while loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me.
#include <iostream>
using namespace std;
int main() {
int s, l;
cout << "Welcome to the letter printer." << endl;
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s%2==0 || s<0)
{
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c')
{
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
return 0;
}
because you are getting char for int variable
wrong:
int s, l;
right one:
int s;
char l;
what is why it goes on infinite loop in second while
explanation for infinite loop
This is how basic_istream works. In your case when cin >> l gets
wrong input - failbit is set and cin is not cleared. So next time it
will be the same wrong input. To handle this correctly you can add
check for correct input and clear&ignore cin in case of wrong input.
incorporated from here
Related
This code gets a series of integers using a while(cin>>x) loop.
The variable x is pushed back on each iteration to vector<int> ivec.
The loops should exit at a non integer input.
After that I want to get one more integer cin>>y to check its freq. inside the vector.
Code:
cout << "Enter a sequence of integers separated with a space: " << flush;
vector<int> ivec;
int x = 0, y = 0;
while( (cin>>x) && (cin.good()) )
{
ivec.push_back(x);
}
cin.clear();
cout << "Enter an integer to count it's frequency: "<< endl;
cin>>y;
cout << "Y: " <<y<< " X: "<<x << endl;
cout << "Occurred "<< count(ivec.cbegin(), ivec.cend(), y)<< " times."<< endl;
for( int i : ivec)
{
cout << " "<<i << flush;
}
cout << endl;
Problem:
When I input a series of integer & the last character is a eof, the while loop gets exited & the second cin>>y never executes.
But the rest of the program executes normally. just no more cin statements can be executed.
The only case where the second cin executes is: if I enter a series of integers separated by a space, press return key, then type the eof (^Z) on a line on its own. I don't know why does it act that way?
What I've tried:
I tried cin.clear(), it does not resolve the problem.
Also I used auto stat = cin.rdstate() before the while loop and cin.setstate(stat) after the loop still the second cin never executes.
ScreenShot:
I know cin ignores space, tab & newline, so why does a new line make a difference?
I am asking this to how cin works and why its behaving this way. I am aware that I can use getline().
I try to identify if a number is an interger or not.
When I run this, I enter a number, such as 5.5, it shows "5.5 is not int. Please try again: ". Then I enter the letter, such as 'a', it shows "5.5 is not int. Please try again: ". The letter 'a' is a character, not integer, I think it should go to the second case and must show "No letter please", but it isn't.
When I first enter a letter, such as 'D', the program run "Please no letter" unlimited times. I wants it shows "Please no letter" but only once, then I can enter another number in this loop.
How can I fix these errors?
while (true) {
while ((num) != static_cast<int>(num)) {
cout << "\t" << num << " is not int. Please try again: ";
cin >> num;
cin.clear();
cin.ignore(80, '\n');
}
while (!(cin >> num)) {
cout << "\tNo letter please: ";
cin >> num;
cin.clear();
cin.ignore(80, '\n');
}
cout << "Good! " << num << " is an int!\n\n";
}
You can do in this way. Enter a string from user. Count the number of characters in that string. If that is equal to string length it is a valid positive integer. For negative integers just check if the number of digits is one less than size of string and string is starting with 0.
#include <iostream>
using namespace std;
int main()
{
string s;
while(true)
{
cin>>s;
int i,no_of_digits=0;
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
no_of_digits++;
}
if(no_of_digits == s.length() || (no_of_digits == s.length()-1 && s[0]=='-'))
{
cout<<"Good "<<s<<" is an Integer.";
break;
}
cout<<s<<" is not a valid Integer!\nPlease Enter again\n";
}
return 0;
}
The best way to parse string in cpp. It's to use stringstream or use sto* series functions of cpp11.
There are already some good answer here.
I just can't seem to get this program to work properly. I can get it to accept two integers and print them to the screen. But I can't get the program to terminate when the '|' is used. Once that its entered it loops infinitely. Here is the code that I have so far:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
You are using the wrong condition in your while loop. You are never changing counter so the loop will never end. However you do change test to false in the while loop if the input fails. You can change the condition of the while loop to use test instead like
while(test)
{
//...
}
Since counter is no longer being used you can get rid of it completely.
Please note that unless you change to taking in string and parsing the input any input that will cause cin to fail will end the loop not just a |.
Just to make clear, I am very new to C++.
But I wrote I very small program to test my skill with arrays and ran into a problem with cin.
If the user enters number, like the program expects them to, all is well. But if a string gets entered, all input is skipped and the program ends.
I set up all of my inputs like this: cin >> x;cin.clear();cin.ignore();
So what is awry??
Here is the full code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
system("cls");
int create = 1;
int entry;
int x;
string chc;
cout << "How long should the array be?" << endl;
cout << ":";
cin >> x;cin.clear();cin.ignore();
if(x<1){x=1;}
int myArray[x];
string askcontinue;
for(int x=0;x<sizeof(myArray)/sizeof(myArray[0]);x++){
system("cls");
cout << "Enter value #" << x+1 << endl;
cout << ":";
cin >> entry;cin.clear();cin.ignore();
myArray[x]=entry;
}
system("cls");
cout << "Index - Value" << endl;
for(int x=0;x<sizeof(myArray)/sizeof(myArray[0]);x++){
cout << x << " ------ " << myArray[x] <<endl;
}
system("cls");
cout << "Restart? [Y/N]" << endl;
cout << ":";
cin >> chc;cin.clear();cin.ignore();
if(chc=="y" || chc=="Y"){main();}
}
cin >> x;cin.clear();cin.ignore();
This thing that you're doing throughout your program is part of the problem. If the user enters something that doesn't meet the formatting requirements for an integer, the stream goes into a failure state. Directly after that happens you clear the stream and discard the next character. If the user entered in more than one character as part of the invalid input, the ignore() call is simply discarding the next character, but not all of the invalid input.
You need to check if the input did not succeed, and then discard the input using the overload of ignore() that takes the number of characters you wish to discard. Do the following if you wish to consistently ask the user for input if he does not provide valid characters:
while (!(std::cin >> x)) {
std::cout << "How long should the array be?" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
But judging from your code, it doesn't look like you want to repeatedly ask the user for input. In that case, you should check for valid input instead and do nothing in the invalid case:
if (std::cin >> x) {
...
}
Also, VLAs (or variable-length arrays) are a non-standard feature of C++, provided as extentions in some compilers. Don't use them. Instead, allocate dynamically by using std::vector:
std::vector<int> myArray(x);
NOTE: you should also change the fact that you defining the variable 'x' three times
the problem you are having, is that c input does not type checking, so it does not care what was entered, so this is up to you. You should input everything as a string, and then make sure that the string contains nothing but numbers, THEN you can use std::stoi, or whatever the appropriate conversion method is. if they DO NOT enter a valid number, then you can just say INVALID, and tell the user to enter a valid number, and go back to the input, you could use something such as:
system("cls");
cout << "Enter value #" << x + 1 << endl;
cout << ":";
cin >> entry; cin.clear(); cin.ignore();
while(!is_valid_integer(entry))
{
system("cls");
cout << "INVALID NUMBER \n Enter value #" << x + 1 << endl;
cout << ":";
cin >> entry; cin.clear(); cin.ignore();
}
myArray[x] = std::stoi(entry);
And then entry is a string.
is_valid_integerwould be defined as:
bool is_valid_integer(std::string str)
{
for(auto it : str)
{
if(!(ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9'))
return false;
//OR: this is more efficient, but is reliant on using ascii codes (which in this case we are)
//if(!(ch >=48 && ch <= 57)) return false;
}
return true;//all numbers
}
This is hw. I have asked my professor why the following code won't exit the while loop, and he/she couldn't tell me. My understanding is that once the input stream has no more values to read, the cin will return a value of false, and should cause the while loop to exit. Mine does not. It seems to keep read the input values (a set of integers) process through the loop, then wait for more input. Can anyone tell me why? Below is the code.
# include <iostream>
using namespace std;
int main()
{
int iEvenSum = 0;
int iOddSum = 0;
int iNum;
// prompt user
cout << "Input any set of integers, separated by a space:\n";
cin >> iNum;
cout << "You input: ";
while (cin)
{
cout << iNum << " ";
if (iNum % 2 == 0)
iEvenSum = iEvenSum + iNum;
else
iOddSum = iOddSum + iNum;
cin >> iNum;
}
cout << "\n\nThe sum of Even numbers is " << iEvenSum << "." << endl;
cout << "The sum of Odd numbers is " << iOddSum << "." << endl;
return 0;
}
while(cin) remains true as long as the cin stream is ok and becomes false if cin encounters an end of file character or an error.
In your case, while(cin) will keep on reading the numbers until it encounters an EOF character or an error. Type Ctrl-D when you don't have any more input numbers and it should quit the while loop