我刚刚开始学习C语言,我需要程序方面的帮助。这是代码。问题:
#include <stdio.h> #include <string.h> #include <stdlib.h>
#define INPUT_LENGTH 128
#define FIELD_LENGTH 30
#define NUM_FIELDS 9
int main()
{
FILE *data=NULL;
char input[INPUT_LENGTH];
char customerData[NUM_FIELDS][FIELD_LENGTH];
int element=0;
char *next;
char ch;
data= fopen("data.txt","r");
if(data!=NULL)
{
//token=strtok(input,"|");
/*while loop will go through line by line and stored it in an input array*/
while(fgets(input,INPUT_LENGTH,data)!= NULL)
{
next=strtok(input,"|");
while(next!=NULL)
{
//ch=getchar()
//>probably a get char for ch
strcpy(next,customerData[element][strlen(next)]);
/*need to put the values into customer data one by one*/
printf("%s\n",next);
//element+=1;
next=strtok(NULL,"|");
}
//element=0;
}
printf("program is done\n");
}
fclose(data);
return 0;
}
通常,“帮助我编写代码”问题在Stack Overflow上是不重要的。为了使该问题保持话题性,我将仅关注如何访问2D char数组的问题。
是的,这是一个2D字符数组。或者换一种说法,它是一个包含NUM_FIELDS
个元素的数组,其中该数组的每个元素都是一个包含FIELD_LENGTH
个元素的char数组。
有很多将数据插入2D char数组的方法,但我可能经常遇到两种。您选择使用哪一个取决于您对这个数组的看法。
考虑此变量的第一种方法只是将其作为2D字符数组-您可以访问的元素网格。在这里,您可以简单地使用常规赋值运算符输入值。您需要确保索引在范围内,否则您将开始访问无效的内存。
//Set a known element that's definitely in range
customerData[1][2] = 'A';
//Loop through all the elements
for(int ii = 0; ii < NUM_FIELDS; ii++)
{
for (int jj = 0; jj < FIELD_LENGTH; jj++)
{
customerData[i][j] = 'B';
}
}
//Set an element from variables
char nextInput = getNextCharFromInput();
if(x < NUM_FIELD && y < FIELD_LENGTH)
{
customerData[x][y] = nextInput;
}
//Bad. This could corrupt memory
customerData[100][60] = 'X';
//Risky without check. How do you know x and y are in range?
cusomterData[x][y] = 'X';
您当然可以通过一次在字符上分配这些元素来编写代码。但是,您程序的更广泛的上下文对我而言意味着下一个选择更好。
在C中,“字符串”只是一个字符数组。因此,查看此变量(以及对该程序最有意义的变量)的另一种方法是将其视为长度为NUM_FIELDS的一维数组,其中每个元素都是长度为FIELD_LENGTH的字符串。
以这种方式来看,您可以开始使用C字符串函数将数据输入到数组中,而不需要逐个字符地处理。和以前一样,您仍然需要注意长度,以免超出字符串的结尾。
还要注意,所有数组decay都包含在指针中,所以char*
也是一个字符串(长度未知)。
//Set a specific field to a known string, which is short enough to fit
strcpy(customerData[2], "date");
//Loop through all fields and wipe their data
for(int ii = 0; ii < NUM_FIELDS; ii++)
{
memset(customerData[ii], 0, FIELD_LENGTH);
}
//Set field based on variables
if(x < NUM_FIELDS)
{
//Will truncate next if it is too long
strncpy(customerData[x], next, FIELD_LENGTH);
//Will not input anything if field is too long
if(strlen(next) < FIELD_LENGTH)
{
strcpy(customerData[x], next);
}
}
//Bad. Could corrupt memory
strcpy(customerData[100], "date");
strcpy(customerData[1], "this string is definitely much longer than FIELD_LENGTH");
//Risky. Without a check, how do you know either variable in in range?
strcpy(customerData[x], next);
getchar和fgetC都分别处理stdout和文件中的reading字符,因此不能用于将数据放入变量。 putchar确实处理将字符放入事物中,但仅处理stdout,因此不能在此处使用。