0

I am going to have a user give me 20 numbers, separated by commas.

Why is it that I can not specify the dimension of an aray and “directly” assign the users input to this array? Or, is it possible to do this, but I have just been typing my code wrong to achieve this?

I have been looking at looking at the strtok function, but wouldn’t that turn the array into a char array as the commas will be present? I would like the array to be an int, as the user will be giving me integers only. Any ideas will be greatly appreciated.

Thank you!

Michel
  • 119
  • 1
  • 3
  • Have a look at `atoi` or `sscanf` as well. Can you post your code here? – babon May 10 '18 at 09:34
  • Look at this answer: https://stackoverflow.com/questions/21837521/how-to-read-in-user-entered-comma-separated-integers – EylM May 10 '18 at 09:39
  • By “directly”, I meant if I could use scanf to assign the users input to an array of the right size... I thought this would work, but after playing around with this I found that this did not work as I would have hoped. – Michel May 10 '18 at 09:40
  • Unfortunately, `scanf` already has a defined interface for how it retrieves and stores input. If you have a specific question about that, please extend your question with your attempt, the expected result, the actual result, why you expected it to work, and what investigation you have already done to determine why it doesn't work. – jxh May 10 '18 at 09:45
  • `strtok` can be used to chop your comma separated line into the segments of the things between the commas. You can then pass those to a function that converts the string into an integer value. However, you may be able to apply `strtol` directly. – jxh May 10 '18 at 09:47
  • Voting to close due to lack of a program illustrating a specific problem. – jxh May 10 '18 at 10:01
  • Related: https://stackoverflow.com/q/41798744/315052 – jxh May 10 '18 at 10:02

2 Answers2

1

There are 2 alternate approaches to using strtok for your goal:

  • you can input the numbers in a loop:

    int array[20];
    int n;
    for (n = 0; n < 20 && scanf("%d", &array[n]) == 1; i++)
        continue;
    printf("%d numbers were input\n", n);
    
  • you can read a full line of input and use strtol() to convert the numbers:

    int array[20];
    int n = 0;
    char buf[256];
    if (fgets(buf, sizeof buf, stdin)) {
        char *p, *q;
        for (p = buf, n = 0; n < 20; n++) {
            array[n] = strtol(p, &q, 10);
            if (p == q)
                break;
            p = q;
        }
        printf("%d numbers were input\n", n);
    }
    
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-1
#include<stdio.h>
#include<string.h>
void main()
{
  char str[100];    
  gets(str);
  char *arr = strtok(str,",");
  while (arr!=NULL)  {
    printf("\n%s", arr);    
    arr = strtok(NULL,","); 
  }
  puts(arr);
}
Mohit
  • 1
  • 2