-2

If a user inputted:

1 2 3 4 5 0

How would I transform it into an array with 5 elements (The 0 integer indicates termination)? Also, in the code I need to ensure it works for up to 500 integers.

I have no clue how to proceed. I am thinking of using gets and saving it into an allocated space:

char *ptr;
ptr = malloc(sizeof(char) * 1000);
fgets(ptr, sizeof(char)*1000, stdin);

The problem here is I am not sure how to allocate the space as each digit will be saved as a character and each integer may have different number of digits.

Afterwards, I am not sure how to split it into array.

Could someone advise me on how to continue or if my method is not good?

I know I have not done a lot but I am really confused. I have looked up on gets(), fgets(), scanf(), fscanf(), and am still not sure.

Thanks!

J...S
  • 5,079
  • 1
  • 20
  • 35
dng
  • 1,275
  • 1
  • 8
  • 10

3 Answers3

1

You could use a character array with a combination of fgets() and strtok().

First declare a character array str and set a flag variable.

char str[100];
int flag=1;

flag may be made 0 when input 0 is found.

As long as flag is 1 use fgets() to read a line of input (provided fgets() is successful) as in

while(flag==1 && fgets(str, sizeof(str), stdin)!=NULL)
{
    .....
    .....
} 

Now inside this loop, use strtok() to tokenize the string in str using space and \n as delimiters. \n is made a delimiter because fgets() reads in the trailing \n to str as well.

for(ptr=strtok(str, " \n"); ptr!=NULL; ptr=strtok(NULL, " \n"))
{
    n=atoi(ptr);
    if(n==0)
    {
        flag=0;
        break;
    }
    printf("\n%d", n);  
}

Convert the tokens produced by strtok() to integers. I used atoi() for brevity but it is not the best way. strtol() might be a good idea. See here.

J...S
  • 5,079
  • 1
  • 20
  • 35
1

You can parse the line input by the user with sscanf() or strtol():

#include <stdio.h>

int main() {
    char buf[256];
    int array[5];

    if (fgets(buf, sizeof buf, stdin)) {
        if (sscanf(buf, "%d%d%d%d%d", &array[0], &array[1], &array[2], &array[3], &array[4]) == 5) {
            // array has the 5 numbers input by the user.
            printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);
        }
    }
    return 0;
}

For generic code that works up to 500 numbers, you can just use scanf() in a loop:

#include <stdio.h>

int main() {
    int array[500];
    int i, n;

    for (n = 0; n < 500; n++) {
        if (scanf("%d", &array[n]) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (array[n] == 0) {
            // 0 indicates termination
            break;
        }
    }
    // the array has n valid non-zero numbers
    printf("The numbers are:\n");
    for (i = 0; i < n; i++) {
        printf("  %d\n", array[i]);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Could you please explain the logic behind the looped scanf? My impression is that the code pauses at the scanf and waits for input. Then when I type "1 2 3 4 5 0" and then hit enter, the code reads the "1" goes through the loop, then reads the "2" until it reads "0". Is this correct? – dng Jun 10 '18 at 15:10
  • 1
    The code pauses if there is no pending input in `stdin`. If the user typed multiple numbers on the same line, they will be parsed one at a time by the individual calls to `scanf()`, each consuming some optional initial whitespace, an optional sign and all the digits of the next number. The code will not pause at all if the user input `1 2 3 4 5 6 0` on one line. – chqrlie Jun 10 '18 at 22:13
-1

I would suggest something like this

#include "rlutil.h" //a good library similar to conio.h or it's Linux equivalent but cross-platform. You have to include it manually and download it at github.

int i = 0;
int num = 1;
char input;
int array[255];
for (i = 0; num = 0; i++)
{
     input = getchar();
     num = input - '0';
     array[i] = num;
     printf("%i ", num);
}

Just pay attention to the size of the array.

Furthermore you could parse the string you got with fgets with strtok. If you want I can edit this post later and include this variant.

alexfwulf
  • 199
  • 1
  • 13