Home > Mobile >  C Multiple Input in One Line
C Multiple Input in One Line

Time:05-09

I am solving Problem 'Red Light Green Light' with code 'DOLL' on Code chef.

ERROR

CodePudding user response:

You need to ask yourself a couple of questions:

  • do you need to check for "invalid" input, and reject cases where the input is split over multiple lines.
  • do you need to read all the numbers on a line of input WITHOUT knowing before hand how many there are supposed to be.

If the answer to both of those is no, there's no reason to check or care about what is on one line vs what is on another. Just use scanf to read numbers and don't worry about spacing or what is on which line.

scanf("%d", &test_cases);   // number of test cases
for (int i = 0; i < test_cases;   i) {
    scanf("%d%d", &N, &height);  // number of values and boundary height
    int val[N];
    for (j = 0; j < N;   j)
        scanf("%d", &val[j]);

Note that there are never any spaces or newlines in the scanf format strings. You don't need them, and they might cause confusion. You just read numbers. If you're paranoid, you can check the return value of scanf -- it should always be the number of items read (1, 2, or 1 in the 3 calls above), but if it is not, the only useful thing you can do is print an error message and exit.

If you do need to care about the newlines (most commonly because you don't know how many numbers will be on a line), use fgets sscanf:

char buffer[MAXLINE];  // buffer big enough for the largest line
int vals[MAXVALS];     // array large enough for the maximum number of vals
char *p = fgets(buffer, sizeof(buffer));    // read a line
int N = 0, len;
while (N < MAXVALS && sscanf(p, "%d%n", &vals[N], &len) == 1) {
    p  = len;
      N; }

CodePudding user response:

Change char name; to char name[1024]; or something similar. char name; is not a string but a single character. fgets and strtok is looking for a pointer to a string but getting a character variable.

  •  Tags:  
  • c
  • Related