Straightfw
Straightfw

Reputation: 2211

A loop works one iteration less than it should

While working with different things I want to perform on every line of input, I stumbled upon a problem - a simple code illustrating what I mean is as follows:

#include<cstdio>
using namespace std;

int main()
{
    char testCstring[100];
    int howManyLines;

    scanf("%d", &howManyLines);
    for(int i = 0; i < howManyLines; ++i)
    {
        fgets(testCstring, 100, stdin);
    }
}

So it's really basic - nothing more than iterating howManyLines times to read a line from input (of course normally I perform some things with it later on, just cut it out here to show the problem). To my surprise, it always runs one iteration less than it should, thus allowing me to input no line if I give him 1. How come? Of course substituting some printf for fgets makes the loop behave normally. Why does it skip one iteration here?

Upvotes: 0

Views: 85

Answers (2)

Eyenseo
Eyenseo

Reputation: 83

That was interesting!

stdin was not empty - after entering the number you pressed return and the new line char is still in stdin.

if you want to use cstdio you would have to 'clean' the stream.

#include<cstdio>
using namespace std;

int main()
{
    char testCstring[100];
    char c;
    int howManyLines;

    scanf("%d", &howManyLines);

    while ((c = getchar()) != '\n' && c != EOF);

    for(int i = 0; i < howManyLines; ++i)
    {
        fgets(testCstring, 100, stdin);
    }
}

Upvotes: 0

Paige Ruten
Paige Ruten

Reputation: 176655

Try changing scanf("%d") to scanf("%d\n"). Otherwise it will read whatever comes after the number (which may be an empty string) as the first line.

Upvotes: 4

Related Questions