简体   繁体   English

将由逗号分隔的数字组成的用户输入放入数组中?

[英]Putting users input consisting of numbers separated by commas into an array?

I am taking in 10 numbers from the user (user enters them at a prompt, and the numbers are separated by commas, as so: 245645, -243, 4245). 我正在从用户那里输入10个数字(用户在提示符下输入它们,并且数字之间用逗号分隔,例如:245645,-243、4245)。 How can I put these elements into an array? 如何将这些元素放入数组? As shown below, I have used scanf which does not work as I had hoped. 如下所示,我使用了scanf ,但效果并不理想。 Any suggestions would be appreciated. 任何建议,将不胜感激。

//User will pass ten numbers, separated by commas. This is to be put into an array.

#include <stdio.h>

int main () 
{
    int A[10]; // array to contain in users input.
    printf("Enter your numbers: ");
    scanf("%d", &A[10]);

    return 0;
}

You have to consume the comma as well in scanf : 您还必须在scanf使用逗号:

for(int i=0; i<10; i++) {        /* for each element in A */
  if(0==scanf("%d,", &A[i])) {    /* read a number from stdin into A[i] and then consume a commma (if any) */
    break;                       /* if no digit was read, user entered less than 10 numbers separated by commas */
    /* alternatively error handling if fewer than 10 is illegal */
  }
}

I won't write the whole thing for you. 我不会为你写全部内容。 But I can definitely help. 但是我绝对可以帮上忙。 One of the ways to do that will be: 做到这一点的方法之一是:

  1. Get a string that contains 10 comma-separated numbers: fgets() may be? 获取一个包含10个逗号分隔数字的字符串: fgets()可能是?
  2. Validate the string, trim white-spaces as well, makes life easier 验证字符串,也修剪空白,使生活更轻松
  3. Pick out a number from string: strtol() may be? 从字符串中选择一个数字: strtol()可能是?
  4. Search for a ',' character in the string, and set pointer to the next index after ',' : strchr() may be? 在字符串中搜索','字符,并将指针设置为','之后的下一个索引: strchr()可能是?
  5. Repeat steps 3 and 4 for a total of 10 times (from here, 9 times actually) 重复步骤3和4,共10次(从这里开始,实际上是9次)
  6. Print the numbers 打印数字

The code below would do half of your job. 下面的代码可以完成一半的工作。 The only remaining part would be to get string from user and validate it. 剩下的唯一部分是从用户那里获取字符串并进行验证。 The intention to have a string declared and initialised upfront is to put more emphasise on actual parsing of data which appear complicated to beginners (no offence). 预先声明并初始化字符串的目的是更加强调对初学者来说似乎很复杂的数据的实际解析(无犯罪)。

Before we look at the code below, lets read a few things first. 在我们看下面的代码之前,让我们先阅读一些东西。

  • You might want to take a look at the man page for strtol() function 您可能想看看strtol()函数的手册页
  • You might want to take a look at the man page for fgets() function, which is not used in the code below, but you may end-up using it to achieve step 1. 您可能想看一下fgets()函数的手册页,该代码在下面的代码中未使用,但最终可能会用它来实现步骤1。

I already concede the fact that this may not be the best way to achieve it, and I would happily agree that this code below can be made better in thousand ways by adding various error check, but I leave that to you to explore and implement. 我已经承认,这可能不是实现它的最佳方法,我很高兴地同意,通过添加各种错误检查,可以以千种方式更好地改进下面的代码,但我留给您探索和实现。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void) 
{
    int i = 0, j = 0;
    char *Str = "1,11,21,1211,111221,312211,1234,4321,123,789";
    char *ptr;
    long ret;
    long array[10] = { [0 ... 9] = 0 };

    // So, lets assume step 1 and 2 are taken care of.

    // Iterate though the data for 10 times
    for(i = 0; i < 10; i++)
    {
        ret = strtol(Str, &ptr, 10);
        // Check if its a number
        if(ret != 0)
        {
            // Its is a number!
            // Put it in the array
            array[j] = ret;
            // Increment the index so that next number will not over-write the existing one
            j++;
            // Find the next ',' in the string  
            Str = strchr(Str, ',');
            if(Str == NULL)
            {
                // Handle this condition that there are no more commas in the string! 
                break;
            }
            // Assuming that the ',' is found, increment the pointer to index next to ','
            Str++;
        }
    }

    // Print the array
    for(i = 0; i < j; i++)
        printf("%ld\n", array[i]);
}

This prints the following output: 这将输出以下输出:

1
11
21
1211
111221
312211
1234
4321
123
789

Hope I have got you started, Good luck. 希望我能帮助您入门,祝您好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM