所以,我正在尝试检测字符串中的单个字符。除了空格和空字符外,不能有其他字符。这是我的第一个问题,因为我的代码检测到包含其他字符的字符串中的字符(除了空格)。
我的第二个问题是,我似乎无法弄清楚如何最好地从文件中读取矩阵。我应该阅读第一行并获得ROWS x COLUMNS。然后我应该将数据读入一个全局存储的矩阵数组中。然后将第二个矩阵读入第二个矩阵阵列(也全局存储)。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#define MAXLINE 100
typedef struct matrixStruct{
int rows;
int columns;
}matrixStruct;
typedef int bool;
enum{
false,
true
};
/*
*
*/
int aMatrix1[10][10];
int aMatrix2[10][10];
int multiMatrix[10][10];
int main(int argc, char** argv){
FILE *inputFile;
char tempLine[MAXLINE], *tempChar, *tempString;
char *endChar;
endChar = (char *)malloc(sizeof(char));
(*endChar) = '*';
bool readFile = true;
inputFile = fopen(argv[1], "r");
if(inputFile == NULL){
printf("File %s not found.\n", argv[1]);
perror("Error");
exit(EXIT_FAILURE);
}else{
printf("File opened!\n");
}
int numRow, numColumn, i, j, tempNum, count = 0;
do{
fgets(tempLine, MAXLINE, inputFile);
tempChar = strchr(tempLine, '*');
if(tempChar != NULL){
printf("True @ %s\ncount=%d\n",tempChar,count);
readFile = false;
}else{
sscanf(tempLine, "%d %d", &numRow, &numColumn);
count++;
for(i=0;i<numRow;i++){
fgets(tempLine, MAXLINE, inputFile);
for(j=0;j<numColumn;j++){
aMatrix1[i][j] = atoi(tempNum);
}
}
}
}
while(readFile);
printf("aMatrix1[%d][%d]= \n", numRow, numColumn);
for(i=0; i < numRow;i++){
for(j=0; j < numColumn; j++){
printf("aMatrix[%d][%d] = %d\t", i, j, aMatrix1[i][j]);
}
printf("\n");
}
return (EXIT_SUCCESS);
}
答案 0 :(得分:0)
对于第一个问题,你可以做你在评论中建议的内容(regexp在这里是一种过度杀戮) - 循环遍历字符串,打破任何不符合你期望的非空白字符,并计算匹配的字符 - 你不想要0场比赛,我猜也不会超过1.
但是,我建议您阅读strtok的手册页 - 我通常不会建议它,因为它不是线程安全的并且有奇怪的行为,但在这个简单的情况下它可以正常工作 - 提供空格字符作为分隔符,并且它会返回第一个非空白字符串。如果没有用“*”strcmp,或者下一次调用strtok没有返回null,那么它就不匹配了。
顺便说一句 - 您打算如何处理不是“.. * ..”或“ROWS x COLUMNS”的行?你现在没有处理它们。
关于第二个问题 - strtok再次可以解决问题 - 重复调用只会给你空格分隔的数字(作为字符串),并且你将能够为每次迭代填充tempNum。