繁体   English   中英

C、从单个输入行读取多个数字

[英]C, reading multiple numbers from single input line

我需要创建处理许多情况的 ac 程序。

为了轻松解决所有情况,我需要将所有输入元素放在一行中,用逗号分隔。

例如用户给定的输入是这样的

5,60,700,8000

应该创建一个像这样{5,,,60,,,700,,,8000}的数组,这意味着数组的大小为 7 并且 a[1],a[3],a[5] 的值是逗号,

谢谢你

无需存储, 使用类似于

int a[4];
scanf("%d,%d,%d,%d", &a[0], &a[1], &a[2], &a[3]);

如果您需要将逗号放回去以便稍后打印,您可以使用

printf("%d,%d,%d,%d", a[0], a[1], a[2], a[3]);

编辑:实际上有几种方法可以满足您的要求:结构数组(可能包含多种数据类型)、带有联合的结构数组(允许运行时选择数据类型)、字符串数组(需要转换数值)

从字面上构造一个包含数字和字符串变量类型的数组的唯一方法是使用 union 显然(并且通常)有更好的方法来处理字母数字数据字符串,但是由于在您的问题下的评论中提到了联合,我将使用该方法来解决您非常具体的要求:

以下示例的结果:
在此处输入图像描述

代码示例:

typedef union   {
    int num;      //member to contain numerics
    char str[4];  //member to contain string (",,,")
}MIX;
typedef struct  {
    BOOL type;//type tag:  1 for char , 0 for number
    MIX c;
}ELEMENT;

ELEMENT element[7], *pElement;//instance of array 7 of ELEMENT and pointer to same

void assignValues(ELEMENT *e);

int main(void)
{
    char buf[80];//buffer for printing out demonstration results
    buf[0]=0;
    int i;

    pElement = &element[0];//initialize pointer to beginning of struct element

    //assign values to array:
    assignValues(pElement);

    for(i=0;i<sizeof(element)/sizeof(element[0]);i++)
    {
        if(pElement[i].type == 1)
        {   //if union member is a string, concatenate it to buffer
            strcpy(element[i].c.str, pElement[i].c.str);
            strcat(buf,pElement[i].c.str); 
        }
        else
        {   //if union member is numeric, convert and concatenate it to buffer
            sprintf(buf, "%s%d",buf, pElement[i].c.num); 
        }
    }
    printf(buf);

    getchar();

    return 0;   
}

//hardcoded to illustrate your exact numbers
// 5,,,60,,,700,,,8000
void assignValues(ELEMENT *e)
{
    e[0].type = 0; //fill with 5
    e[0].c.num = 5;

    e[1].type = 1; //fill with ",,,"
    strcpy(e[1].c.str, ",,,");

    e[2].type = 0; //fill with 60
    e[2].c.num = 60;

    e[3].type = 1; //fill with ",,,"
    strcpy(e[3].c.str, ",,,");

    e[4].type = 0; //fill with 700
    e[4].c.num = 700;

    e[5].type = 1;  //fill with ",,,"
    strcpy(e[5].c.str, ",,,");

    e[6].type = 0; //fill with 8000
    e[6].c.num = 8000;
}

暂无
暂无

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

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