Home > Blockchain >  How to accept indefinite inputs on a singular scanf() line in C
How to accept indefinite inputs on a singular scanf() line in C

Time:08-15

I am trying to get an indefinite input of numbers (max 50) to create a program that does the following:

INPUT:
Enter Numbers: 20 15 5 8 16 12
^D

OUTPUT:
20 | ********************
15 | **********
 5 | *****
 8 | ********
 etc...

I am having trouble getting user input in the way specified. This is my current code, which requires the user hit enter in the terminal between each input value. I'm not looking for a solution to the entire problem, just how I can get input as shown above. The '^D' is supposed to specify when the user is done. I haven't implented it in my code as I'm confused as to how.

#include <stdio.h>

#define MAX_SIZE 50

int
main (){

printf("Enter numbers: ");
for(int i = 0; i <= MAX_SIZE; i  )
{
    int a;
    scanf("%d", &a);
}

return 0;
}

Thank you!

CodePudding user response:

Here is something to get you started:

#include <stdio.h>

#define MAX_SIZE 50

int main(void)
{
    int arr[MAX_SIZE];
    int n=0;
    
    while(n < MAX_SIZE) {
        int a;
 
        if(scanf("%d", &a) != 1) break;
 
        arr[n  ]=a; 
    }
    
    // The table is not implemented
    puts("");
    for(int i=0; i<n; i  ) printf("%d ", arr[i]);
}

CodePudding user response:

Here's a solution that achieve the desired result:

#include <stdio.h>

#define MAX_SIZE 50

int main(int argc, char** argv)
{
    int array[MAX_SIZE];
    int used_indexes = 0;
    char ch = '*';

    printf("Enter numbers:\n");
    for (int i = 0; i < MAX_SIZE; i  )
    {
        int value;
        if (scanf_s("%d", &value) <= 0)
            break;
        array[i] = value;
        used_indexes  ;
    }

    printf("\n\nResult:\n");
    for (int i = 0; i < used_indexes; i  )
    {
        printf("= | ", array[i]);
        for (int j = 0; j < array[i]; j  )
            printf("%c", ch);
        printf("\n");
    }
    
    return 0;
}

CodePudding user response:

You need to dynamically allocate space for your data (as you do not know the size of it in advance).

Use functions - do not program in the main function

int *addtoArray(int *arr, size_t *size, int val)
{
    arr = realloc(arr, (*size   1) * sizeof(*arr));

    if(arr)
    {
        arr[*size] = val;
        *size  = 1;
    }
    return arr;
}

int *readIntegers(int *arr, FILE *fi, size_t *size, const size_t maxcount)
{
    /* addd some parameter chaeck here */
    int val;
    while(fscanf(fi, "%d", &val) == 1)
    {
        int *tmp = addtoArray(arr, size, val);
        if(tmp) arr = tmp;
        else { /* error handling*/ }
        if(*size == MAXSIZE) break;
    } 
    return arr;
}


int main(void)
{
    int *arr = 0;
    size_t size = 0;

    arr = readIntegers(arr, stdin, &size, MAXSIZE);

    printf("Elements scanned: %zu\n", size);
    free(arr);
}

https://godbolt.org/z/qeKPfGM3c

  • Related