1

I'm attempting to get an input of numbers via the format:

c1 c2 [c1 amount of integers separated by white space] [c2 amount of integers separated by white space]

And assigning the numbers in different places based on whether they are in the c1 segment, or c2 segment.

This means I have to read and use c1 and c2 as variables in a for loop after scanning the first two values.

Here's my code:

scanf("%d %d ", &np, &nm); // np and nm are c1 and c2

for (j = 0; j < np; j++)
{
    scanf("%d ", &tempvalue);
    // assign tempvalue to somewhere via a function
}
for (j = 0; j < nm; j++)
{
    scanf("%d ", &tempvalue);
    // assign tempvalue elsewhere via a function
}

But for whatever reason, debugging with print statements show that after the first assignment for c1, the program is asking for an input again (the input buffer cleared??) Any idea why this might be the case?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Ymi
  • 609
  • 6
  • 18
  • 1
    Well, after `scanf("%d %d ", &np, &nm)`, it will ask for input again with `scanf("%d ", &tempvalue)`, right? Is that what you mean? – Owen Apr 16 '21 at 12:29
  • @Owen no, everything has to be put in one line. so for example: 1 1 1 1, or 1 2 1 1 2, 3 2 1 1 1 2 2, the first two numbers dictate how many integers will follow – Ymi Apr 16 '21 at 12:30
  • @anastaciu it is the required input format of the problem im trying to solve. – Ymi Apr 16 '21 at 12:31

1 Answers1

1

The %d specifier automatically discards blank spaces between the inputed numbers, remove the all the spaces from scanf specifier, they are not needed and just mess up your input, especially the ones at the end.

Note that for a more robust code you should verify the return value of scanf, i.e. if it maches the number of values to be read, and guard against invalid inputs i.e. non-digit inputs.

Here is a good example: https://stackoverflow.com/a/40552127/6865932

Ideally you would use fgets to get the input and sscanf or strtol to parse, if it conforms with your specs.

anastaciu
  • 23,467
  • 7
  • 28
  • 53