0

I will be getting three lines of input. The first line will give me 2 integers and the third line will give me 1 integer. But the second line can give me any number of integers ranging between 1 to 100. For example, the input could be:

2 1
5 6 1 9 2
10

or could be:

10 4
5 6
9

I can read the second line of integer input into an integer array for a fixed number of integers, but cannot do so for a varying number of integers. I suppose, in this case, I should use a while loop which will break when scanf() finds a newline. How do I code that?

Shabbir Khan
  • 187
  • 1
  • 8

2 Answers2

3
  1. Read the line into a buffer (@John Coleman) using using fgets() or getline().

  2. Parse the string looking for whitespace that may contain a '\n', exit loop if found. Then call strtol() or sscanf() to read the 1 number. Check that function's return value for errors too.

  3. Repeat above steps.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

I am actually a newbie in programming and am unaware of most of the functions. The only string functions I know of are strlen() and strcmp(). And my i\o function knowledge is limited to printf() and scanf().

Anyhow, I solved my problem in this way:

int a[101];
int i, num;
char ch;

for (i = 0; i < 101; i++)
    a[i] = 0;

while (1)
{
    scanf("%d%c", &num, &ch);
    i = num;
    a[i] = num;
    if (ch == '\n')
        break;
}

This works! The value of num had to be equal to the value i because my program needed it.

Shabbir Khan
  • 187
  • 1
  • 8
  • Notes: 1) `for (i = 0; i < 101; i++) a[i] = 0;` writes outside `a[]` which is _undefined behavior_ 2) `scanf("%d%c", &num, &ch);` does not check the result of `scanf()`, so code does not know the values of `num`, `ch` are valid. – chux - Reinstate Monica Nov 06 '15 at 15:19
  • @chux Thank you for pointing those things out. I fixed the first thing you mentioned. Next, I didn't check if `num` and `ch` are valid or not because it was competitive programming problem and we were only given integer inputs. However, your insight will be useful in real life problems. I appreciate that. – Shabbir Khan Nov 06 '15 at 15:30
  • @chux I fixed it according to your suggestion. – Shabbir Khan Nov 08 '15 at 15:41