I'm writing a simple program that takes an a series of integers, store them in a vector, and prints out the sum of 'x' number of ints in the vector. However the compiler seems to skip over my program after printing "how many integers would you like to add together?" after printing 0 to the screen.
std::vector<int>values;
int v = 0;
int it = 0;
int sum = 0;
int main() {
std::cout << "Enter values" << std::endl;
while (std::cin >> v) {
values.push_back(v);
}
std::cout << "how many integers would you like to add together?" << std::endl;
std::cin >> it;
for (int i = 0; i <= it - 1; ++i) {
sum += values[i];
}
std::cout<<sum;
}
In order to exit from the first while loop, you must have triggered end-of-file condition on cin (e.g. by pressing Ctrl+D with some shells). By the time std::cin >> it is reached, the stream is still in end-of-file state, so the read operation fails and it retains its value of zero.
Related
I was solving some exercises to pass the time, and I encountered a behaviour I didn't understand, I am going to explain:
The exercise:
Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First, ask for N, then read the values into a vector, then calculate the sum of the first N values.
Since I asked for N as the second step:
In the second std::cin (std::cin >> values_to_compute) it has to leave the while statement to continue the program, "only possible if" what is read is not a double. So I can type, for example; 'k' or "how are you?" or Ctrl + Z (I am on Windows 10).
int main() {
try {
double holder {0};
std::vector<double> values;
while (std::cin >> holder) {
values.push_back(holder);
}
std::cin.clear();
std::cout << "Out of the loop, now entering to the other std::cin\n";
int values_to_compute {0};
std::cin >> values_to_compute;
std::cout << "Computing...\n";
double result_computed {0};
for (int i {0}; i < values_to_compute; ++i) {
result_computed += values[i];
}
std::cout << "Result computed " << result_computed << '\n';
system("pause");
return 0;
}
catch (std::runtime_error& e) {
std::cerr << e.what() << '\n';
system("pause");
return 1;
}
}
Ok so?
So... std::cin leaves the while in a not good() state. I have to call std::cin.clear() to be able to use std::cin again.
Ok, and?
Well, if I type Ctrl+Z to exit the while loop, the std::cin.clear() works; if I type something that is not Ctrl + Z the std::cin.clear() doesn't work.
I want to know the why of that behaviour.
That's because std::cin::clear clears the error state of cin but it does not remove the data from the stream. You can use std::cin::ignore() to read and discard a line of text before reading values_to_compute.
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Make sure to #include <limits> to get std::numeric_limits.
I would like to create a c++11 program that takes in 10 positive integers and gives the user the total. In the event of a negative number or a char input, the exception should be thrown and the user must re enter their value.
The program below works with negative numbers. However, when I enter a character like "a", the program goes into an infinite loop and I cannot figure out why.
Any and all help will be appreciated
#include <iostream>
int main(){
int array[10] = {0};
int total = 0;
for(int i =0; i < 10; i++){
std::cout<<"Number "<< i+1 << ": " <<std::endl;
std::cin >> array[i];
try{
if(array[i] < 0 || std::cin.fail())
throw(array[i]);
}
catch(int a){
std::cout<< a <<" is not a positive number! "<<std::endl;
i-=1; // to go back to the previous position in array
}
}
for(int k = 0; k < 10; k++)
total+=array[k];
std::cout<<"Total: " <<total<<std::endl;
}
If you get invalid input there are two things to thing you need to do:
Clear the stream status. This is done using the clear function.
Remove the invalid input from the buffer. This is usually done using the ignore function.
As for your program, you don't need exceptions here, just using unsigned integers and checking the status is enough:
unsigned int array[10] = { 0 };
...
if (!(std::cin >> array[i])
{
std::cout << "Please input only non-negative integers.\n";
// First clear the stream status
std::cin.clear();
// Then skip the bad input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Make sure the index isn't increased
--i;
}
To use exceptions similar to what you do now, the solution is almost exactly the same as above:
unsigned int array[10] = { 0 };
...
if (!(std::cin >> array[i])
{
throw i;
}
catch (int current_index)
{
std::cout << "The input for number " << current_index + 1 << " was incorrect.\n";
std::cout << "Please input only non-negative integers.\n";
// First clear the stream status
std::cin.clear();
// Then skip the bad input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Make sure the index isn't increased
--i;
}
Do not forget to include limits header file while using following line in your code :
std::cin.ignore(std::numeric_limits::max(), '\n');
because numeric_limits template is defined in this header file !
This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have been following a course about algorithms on Coursera and I tried to put what I learned into code. This is supposed to be a "divide & conquer" algorithm and I hope that part is alright. I have a problem I encountered just messing around with it: everything works fine until I input a 12 digit number into the program. When I do that, it just ends the cin and outputs all the previous numbers sorted (blank space if no numbers are before). If you could, please tell me what's wrong if you spot the mistake. This is my code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
// setup global variable for the number of inversions needed
int inversions = 0;
// function to merge 2 sublists into 1 sorted list
vector<int> Merge_and_Count(vector<int>& split_lo, vector<int>& split_hi) {
// setup output variable -> merged, sorted list of the 2 input sublists
vector<int> out;
int l = 0;
int m = 0;
// loop through all the elements of the 2 sublists
for (size_t k = 0; k < split_lo.size() + split_hi.size(); k++) {
// check if we reached the end of the first sublist
if (l < split_lo.size()) {
// check if we reached the end of the second sublist
if (m < split_hi.size()) {
// check which element is smaller and sort accordingly
if (split_lo[l] < split_hi[m]) {
out.push_back(split_lo[l]);
l++;
}
else if (split_hi[m] < split_lo[l]) {
out.push_back(split_hi[m]);
m++;
inversions++;
}
}
else {
out.push_back(split_lo[l]);
l++;
inversions++;
}
}
else {
out.push_back(split_hi[m]);
m++;
}
}
return out;
}
// function that loops itself to split input into halves until it reaches the base case (1 element array)
vector<int> MergeSort_and_CountInversions(vector<int>& V) {
// if we reached the base case, terminate the loop and feed the output to the previous loop to be processed
if (V.size() == 1) return V;
// if we didn't reach the base case
else {
// continue halving the sublists
size_t const half_size = V.size() / 2;
vector<int> split_lo(V.begin(), V.begin() + half_size);
vector<int> split_hi(V.begin() + half_size, V.end());
// feed them back into the loop
return Merge_and_Count(MergeSort_and_CountInversions(split_lo), MergeSort_and_CountInversions(split_hi));
}
}
// main function of the app, runs everything
int main()
{
// setup main variables
int input;
vector<int> V;
// get input
cout << "Enter your numbers to be sorted (enter Y when you wish to proceed to the sorting)." << endl;
cout << "Note: do NOT use duplicates (for example, do not input 1 and 1 again)!" << endl;
while (cin >> input)
V.push_back(input);
cout << "\nThe numbers you chose were: " << endl;
for (size_t i = 0; i < V.size(); i++)
cout << V[i] << " ";
// get sorted output
vector<int> sorted = MergeSort_and_CountInversions(V);
cout << "\n\nHere are your numbers sorted: " << endl;
for (size_t j = 0; j < sorted.size(); j++)
cout << sorted[j] << " ";
// show number of inversions that were needed
cout << "\n\nThe number of inversions needed were: " << inversions << endl;
return 0;
}
12 decimal digits is too long to fit into a 32-bit number, which is how int is usually represented. Reading that number using >> therefore fails and cin >> input converts to a false value, which terminates the loop.
See operator >> documentation for details of handling failure modes.
You can get the maximum number of base-10 digits that can be represented by the type using the std::numeric_limits::digits10 constant:
std::cout << std::numeric_limits<int>::digits10 << '\n';
Chances are the maximum number of significant digits for type int is 9, and you try to supply 12 via standard input. The program doesn't crash, the condition of (cin >> input) simply evaluates to false.
12 digits is too much for 32-bit integer, try to use as unsigned long long int, check these limits:
http://www.cplusplus.com/reference/climits/
I had a strange behavior in a program and I spent long time trying to deduce why. it was an infinite loop with no sense. Testing these lines of code(under suspicion) i got the same result. Every time I type in a non-numeric value such a symbol, the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered. I'd like to know why is that weird behavior from cin, printing all those zeros instead of stopping when it finds a wrong reading.
#include <iostream>
using namespace std;
int main()
{
int n = 0;
while(n >= 0) {
cin >> n;
cout << n << endl;
}
return 0;
}
the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered.
That is not quite right: when you ask cin for an int, but there's no int, you get no value back, but the invalid input remains in the buffer. When you ask for int again in the next iteration of the loop, same thing happens again, and no progress is made: bad data remains in the buffer.
That's why you get an infinite loop. To fix this, you need to add some code to remove bad data from the input buffer. For example, you could read it into a string, and ignore the input:
int n = 0;
while(n <= 0) {
cin >> n;
if (!cin.good()) {
cin.clear();
string ignore;
cin >> ignore;
continue;
}
cout << n << endl;
}
Demo.
You need to "eat" the non-numerical input i.e.
#include <iostream>
using namespace std;
int main()
{
int n = 0;
while(n >= 0) {
cin >> n;
if (!cin) {
char c;
cin >> c;
} else {
cout << n << endl;
}
}
return 0;
}
I have a problem with this code:
int main()
{
int x, sum = 0, how_many;
vector<int> v;
cout << "Write few numbers (write a letter if u want to end)\n";
while (cin >> x)
{
v.push_back(x);
}
cout << "How many of those first numbers do u want to sum up?" << endl;
cin >> how_many;
for (int i = 0; i < how_many; ++i)
{
sum += v[i];
}
cout << "The sum of them is " << sum;
return 0;
}
The problem is that console doesn't let me even write sth into how_many and error occurs. When I put lines 6 and 7 before cout << "Write few..." it all works perfectly. Can someone tell me why is that happening?
The loop ends when cin fails to convert the input into an integer, which leaves cin in a bad state. It also still contains final line of input. Any further input will fail, unless you clear the bad state:
cin.clear(); // clear the error state
cin.ignore(-1); // ignore any input still in the stream
(If you like verbosity, you could specify std::numeric_limits<std::stream_size>::max(), rather than relying on the conversion of -1 to the maximum value of an unsigned type).
You need to clear the cin error state because you ended the int vector read operation by an error.
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');