Why is cin not executing inside for loop? - c++

#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> vec; //vec now acts like a datatype
int main()
{
vec powers; //stores powers of x in the objective function
vec coefficients; //stores coefficients of x in the objective function
double pow;
double coeff = 0;
cout << "Enter powers of x present in the objective function and enter any character to stop" << endl;
cout << "REMEMBER TO ENTER 0 IF CONSTANT EXISTS!" << endl;
while (cin >> pow)
powers.push_back(pow); //Working fine
cout << endl;
for (vec::iterator iter_p = powers.begin(); iter_p != powers.end(); iter_p++)
{
double coeff;
cout << "Enter coefficient of the (x^" << *iter_p << ") term: ";
cin >> coeff; //THIS IS NOT EXECUTING
coefficients.push_back(coeff); //NOT WORKING EITHER
}
cout << endl;
return 0;
system("pause");
}
I want to input powers of a polynomial equation along with coefficients. I am able to store the powers in a vector. But in the for loop I am using to input coefficients, cin is simply not executing. I would be much obliged if someone could out what exactly is causing cin statement to be skipped.

The issue here is you tell the user to enter a character to end
while (cin >> pow)
powers.push_back(pow);
While that works, it also puts cin in an error state and leaves the character in the buffer. You need to clear that error state and get rid of the character left in the input. You would do that by adding
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
after the while loop. clear clears the errors and the call to ignore gets rid of any characters left in the input.

Related

How can I save a string input with blank space in c++ (I am using if else statement)

So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Everything was fine until I came to know that it was not saving the text input with a blank space
I searched how to store string input with blank space and then changed the code but it didn't work.
The changed code was
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Please help
List item
If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
Note: the use of isdigit(y) is superfluous. If you validate the input correctly, you determine whether a valid integer was entered at the time of the read simply by checking the stream-state after the read. If failbit is set, the user did not enter a valid integer.
While fine for test code, you will want to look at Why is “using namespace std;” considered bad practice?
Example Use/Output
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
If I misinterpreted your goal, let me know and I'm happy to help further.
As seen from this answer, you are mixing the >> operator and getline() which causes syncing issues as getline is not waiting for the input to flush.
You can call either
cin.ignore();
or
cin.clear();
cin.sync();
just before getline().
Patched code:
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.ignore();
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}

Which flag in cin turns to false when you enter a wrong type input [duplicate]

I want to check if the input is valid, but when i do run this code I see that it checks only input for charcters. If i input a float number it will take it and going to use like integer without fractional part.
#inclide <iostream>
using namespace std;
...
int n;
cout << "Your input is: "<<endl;
cin >> n;
while (cin.fail()) {
cout << "Error. Number of elements must be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
cin >> n;
}
...
`
So, how to make this code see if the input is float?
You can try to convert the input string to a int using a std::istringstream. If it succeeds then check for eof() (after ignoring blank spaces) to see if the whole input was consumed while converting to int. If the whole input was consumed then it was a valid int.
Something a bit like this:
int input_int()
{
int i;
// get the input
for(std::string line; std::getline(std::cin, line);)
{
// try to convert the input to an int
// if at eof() all of the input was converted - must be an int
if(!line.empty() && (std::istringstream(line) >> i >> std::ws).eof())
break;
// try again
std::cout << "Not an integer please try again: " << std::flush;
}
return i;
}
int main()
{
std::cout << "Enter an integer: " << std::flush;
std::cout << "i: " << input_int() << '\n';
}
Building on Raindrop7's solution, here's the full code to do what you need:
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double m;
cout << "Your input is: "<<endl;
cin >> m;
while (cin.fail() || (m-floor(m)))
{
cout << "Error. Nubmer of elements has to be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
cin >> m;
}
int n = (int)m;
return 0;
}
Here's a sample output:
Your input is:
2.7
Error. Nubmer of elements has to be integer. Try again:
erer
Error. Nubmer of elements has to be integer. Try again:
2
The code below should be able to do what you are hoping to achieve:
#inclide <iostream>
using namespace std;
int n;
cout << "Your input is: "<<endl;
while (!(cin >> n) || cin.get() != '\n') {
cout << "Error. Number of elements must be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
}
The program asks the user to re-enter an integer if either of the following happens:
If the program is unable to extract an integer from the std::cin stream. (For example, when a character or string is entered by the user)
If, after an integer is extracted successfully, the next character in std::cin is not the new line '\n' character. (For example, when a number with a decimal point like 1.1 is entered, or when an integer followed by a character like 1a is entered.)

How do you code, if x is not equal to a number, program will then exit

I am confused about this. For example
#include <iostream>
int main(){
using namespace std;
int x, y;
cout << "enter a number: \n";
cin >> x
if (x != ){ // If user inputs anything besides a number, Program will then exit
cout << "invalid";
}
return 0;
}
what code could i use so that if the user decided to input a letter instead of a number, the program will then output invalid and the program will then exit
The operator >> used in combination with cin returns a reference that can be checked to see if the task of assigning the entry to the integer x was successful. If the operation has failed, meaning that the entry was not an integer, it returns a null pointer. In that case !(cin >> x) evaluates to true.
#include <iostream>
#include <cstdlib> // for exit()
using namespace std;
int main(){
int x;
cout << "enter a number: \n";
if (!(cin >> x) ){// If user inputs anything besides a number, Program will then exit
cout << "invalid entry.\n";
exit(0);
}
cout << "you entered number: " << x << endl;
return 0;
}
See also, e.g., the answers to this question for more information.
Edit:
As an equivalent alternative one can also use cin.fail(). This results in a code that is more easily readable:
cout << "enter a number: \n";
cin >> x ;
if (cin.fail()){
...
}

Entering specific character into while loop

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

Code doesn't proceed beyond input stage

I've constructed a simple program that is supposed to take an amount in cents that the user inputs and outputs it in the form of dollars and cents, however, when I run it, it asks me for the amount, I input it, and the program doesn't proceed. I'm new to programming and would dearly appreciate any help I can get on the matter
#include <iostream>
using namespace std;
int main()
{
int numb;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
cin >> numb;
while (numb>=0);
{
dollars=int(numb/100);
cents=numb%100;
}
cout << dollars << "dollars" << cents << "cents"<<endl;
return 0;
}
The code below should work as you expected.
Read the comments I inserted into your code for more information.
Also, you may want to insert extra check in the loop for invalid input (i.e. non-digit characters) as that will cause the loop to enter an infinite loop.
EDIT: I've updated the code with the extra check to handle invalid non-numeric user input.
#include <iostream>
using namespace std;
int main()
{
int numb = 0;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
// I suspect your while loop here is to keep soliciting input
// if the input is not valid, so I've moved the "cin" into the loop.
// Don't use semi colon here after the while statement because
// in doing so, you're eliminating the body of the loop.
while (numb <= 0)
{
cin >> numb;
if(cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
cout << "Non numeric input, please try again." << endl;
continue;
}
cout << "numb: " << numb << endl;
dollars=int(numb/100);
cents=numb%100;
}
// I've inserted extra spaces around dollars and cents here
// to make the output more readable.
cout << dollars << " dollars " << cents << " cents"<<endl;
return 0;
}
This while loop doesn't make any sense. Remove it.
while (numb>=0); // remove this line and the '{' '}'
{
dollars=int(numb/100);
cents=numb%100;
}
Generally when using loops check that they will terminate. You are checking every iteration that numb>=0 but inside the loop numb never changes it's value. So the program executes this loop forever.
You have an infinite loop with your 'while' block, because numb is always positive (it doesn't change for any iteration).
Try removing the while loop to let the program proceed.
#include <iostream>
using namespace std;
int main()
{
int numb;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
cin >> numb;
dollars=int(numb/100);
cents=numb%100;
cout << dollars << "dollars" << cents << "cents" << endl;
return 0;
}
You can also have a look at other answers that give you ways to use a loop to repeatedly ask for (valid) user inputs.
you made an infinite loop
while (numb>=0);
{
dollars=int(numb/100);
cents=numb%100;
}
numb is let's say 3, so this always 3>=0 equals true therefore, you neverexit that loop