Raees Rajwani
Raees Rajwani

Reputation: 517

stdin not reading last line of input

So I have a program like so:

#include <iostream>
using namespace std;

int factorial(int x) {
    int result = 1;
    for(x; x > 1; --x) {
         result*=x;
    }
    return result;
}


int main() {
    // your code goes here
    int n;
    std::cin >> n;

    for(int i = 0; i < n; ++i) {
        std::cout<< "\n";
        std::cout << "entering for loop ";
        int x;
        std::cin >> x;
        std::cout << "entering fac ";
        std::cout << factorial(x);
        std::cout << "leaving fac ";
        std::cout << "leaving for loop ";
        std::cout << "\n";
    }
    return 0;
}

When I run the program instead of giving the input one at a time I input all of it in all at once into terminal. On giving it input like so:

4

1

2

5

3

The program outputs:

entering for loop entering fac 1leaving fac leaving for loop

entering for loop entering fac 2leaving fac leaving for loop

entering for loop entering fac 120leaving fac leaving for loop

entering for loop

As you see it is not receiving the last value from stdin. Why is this happening, can someone explain?

Upvotes: 0

Views: 128

Answers (1)

alexandre-tsu-manuel
alexandre-tsu-manuel

Reputation: 412

You are likely to have forgotten the last new line.

If you don't press the enter key at the end, the code is still waiting on this line:

std::cin >> x;

Upvotes: 1

Related Questions