我希望您能为我正在为作业编写的程序的这种方法提供一些输入和二维数组方面的帮助。编程语言是 C 我得到了一些输入参数:
FILE * ifp = input file pointer, opened up in main, opened a txt file with a format of 3 strings per line
char ** firstTokens, middleTokens = 2 dimensional char arrays, I want them to hold the first two strings minus expected punctuation at the end of each string (such as commas and periods). Planned to be an output parameter.
char * lastLetter = The first letter of whatever string is in the last column per line in the txt file. Planned to be an output parameter.
int numberOfLines = number of lines I'm expecting to read from the text file
这是对我的主函数中的方法的调用:
readLine(ifp, firstTokens, middleTokens, lastLetter, numberOfLines);
我认为我的问题是正确获取 firstTokens
和 middleTokens
,因为我在编辑时总是遇到编译器错误和段错误。非常感谢对错误的一些帮助/澄清。
void readLine(FILE * ifp, char ** firstTokens, char ** middleTokens, char* lastLetter, int numberOfLines)
{
char* tempFirst;
char* tempMiddle;
char* tempLast;
char delim[4];
delim[0] = '.';
delim[1] = '\0';
delim[2] = '\n';
delim[3] = ',';
int i;
for(i = 0; i < numberOfLines; i++)
{
fscanf(ifp, "%s %s %s", tempFirst, tempMiddle, tempLast);
*firstTokens[i] = strtok(tempFirst, delim);
*middleTokens[i] = strtok(tempMiddle, delim);
lastLetter[i] = tempLast[0];
}
}
最佳答案
您需要为 tempFirst
、tempMiddle
和 tempLast
分配存储空间。 fscanf
写入这些指针,假设您已经为它们提供了足够的内存。
#define MAX_NAME_LEN (20) /* change this as required */
...
char tempFirst[MAX_NAME_LEN];
char tempMiddle[MAX_NAME_LEN];
char tempLast[MAX_NAME_LEN];
...
fscanf(ifp, "%s %s %s", tempFirst, tempMiddle, tempLast);
关于c - 函数的二维字符数组的输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360211/