Need to read an undetermined amount of integers from stdin into an array

前端 未结 1 632
无人共我
无人共我 2021-01-24 01:15

So I\'m writing a practice program that will take integers as input from stdin, load them into an array, sort the array, and then output the results.

I\'ve been struggli

相关标签:
1条回答
  • 2021-01-24 01:56

    The problem is that sscanf doesn't keep a pointer into the buffer. So every time the code calls sscanf it's just getting the first number from the buffer. The result is an infinite loop.

    To fix the problem, you can use the %n conversion specifier. %n returns the number of characters that were used by the conversions. That number (which I call delta in the code below) can be used to update an index into the buffer. Here's how it works, each call to sscanf returns a delta. That delta is added to an index, and the index is used in the expression &buffer[index] to point to the next number in the buffer.

    Here's what the resulting code look like

    // Load stdin into a buffer
    char buffer[100];
    if(fgets(buffer, sizeof(buffer), stdin) == NULL)
        Handle_EOForIOError();
    
    // Get a count of the numbers to create the array
    int numIntegers = 0;
    int index = 0;
    int num, delta;
    while(sscanf(&buffer[index], "%d%n", &num, &delta) == 1)
    {
        numIntegers++;
        index += delta;
    }
    
    // Initialize the array with the proper size
    int *numbers = malloc(numIntegers*sizeof(int));
    
    // Load the integers into the array
    index = 0;
    for ( int i = 0; i < numIntegers; i++ )
    {
        if (sscanf(&buffer[index], "%d%n", &numbers[i], &delta) != 1)
            ComplainBitterlyAndExit();
        index += delta;
    }
    
    0 讨论(0)
提交回复
热议问题