2015-09-23 64 views
-2

我需要创建一个处理很多情况的c程序。C,从单个输入行读取多个数字

为了解决所有的情况很容易我需要把所有的输入元素在一行中用逗号分隔。

例如用户给定的输入这样

5,60,700,8000 

应该创建这样{5,,,60,,,700,,,8000} 阵列,这意味着阵列是尺寸7的和一个[1],[3],A [5]值是逗号,

谢谢

+3

什么是你的问题? – ouah

+0

告诉我们你试过了什么? –

回答

1

编辑:其实有几个方法可以做到你是什么问:结构数组(可能包含几种数据类型),带有union的结构数组(允许运行时选择数据类型),字符串数组(需要转换数值)

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

以下示例的结果:
enter image description here

代码示例:

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; 
} 
1

号无需存储,。使用类似的东西来

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]); 
+0

谢谢你的回答。但在我的程序中,我希望只允许输入之间的逗号,因此需要将逗号存储在数组中,以便我们可以放置一些条件,如[1] =',',如果程序不是 – user1934439

+0

@ user1934439 - 所以你的数组需要存储字符串,而不是数字值,在那种情况下(或者是一个int和一个带有标签的char)的联合)可以用于你的目的吗? –

+0

@ user1934439这并未在您的问题中指出,并提出了完全不同的问题。 – IKavanagh