【问题标题】:Detecting single character in string检测字符串中的单个字符
【发布时间】:2013-09-25 15:17:04
【问题描述】:

所以,我试图检测字符串中的单个字符。除了空格和空字符外,不得有其他字符。这是我的第一个问题,因为我的代码检测字符串中的字符与其他字符(除了空格)。

我的第二个问题是我似乎无法弄清楚如何最好地从文件中读取矩阵。我应该阅读第一行并获得 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);
}

【问题讨论】:

  • 第一个问题:为什么不使用正则表达式?对于第二个问题:您始终可以使用 ReadFile 访问文件数据二进制文件。
  • 像一个while循环在tempLine数组(字符串)中移动,如果不是空格或字符检测,那么转义?我不明白你所说的访问数据二进制是什么意思?

标签: c string matrix stdin detection


【解决方案1】:

对于第一个问题,您可以按照您在评论中的建议进行操作(正则表达式在这里是多余的)- 循环遍历字符串,中断任何不是您期望的非空白字符,并计算匹配的字符 -你不想要 0 个匹配项,我猜也不会超过 1 个。

但是,我建议您阅读 strtok 的手册页 - 我通常不会建议它,因为它不是线程安全的并且具有奇怪的行为,但在这种简单的情况下它可以正常工作 - 提供空白字符作为分隔符,并且它将返回第一个非空白字符串。如果 strcmp 不带“*”,或者如果下一次调用 strtok 不返回 null,则不匹配。

顺便说一句,您打算如何处理不是“.. * ..”或“ROWS x COLUMNS”的行?你现在不处理它们。

至于第二个问题 - strtok 可以再次救援 - 重复调用只会为您提供以空格分隔的数字(作为字符串),并且您将能够为每次迭代填充 tempNum。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2015-11-18
    • 2011-11-02
    • 2015-10-11
    • 2013-05-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多