【问题标题】:Reading until end of line读到行尾
【发布时间】:2012-11-09 21:47:31
【问题描述】:

作为我的项目的一部分,我正在尝试从 C 语言文件中读取。

我的目的是将文件中的单词(由空格、逗号、分号或换行符分隔)解析为标记。

为此,我必须逐字阅读。

do {

    do {

        tempChar = fgetc(asmCode);
        strcpy(&tempToken[i], &tempChar);

        i++;

    } while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');//reading until the given parameters

    i = 0;

    //some other code with some other purpose

} while (tempChar != EOF);//reading until the end of the file

即使下面的代码从文件中读取,它也不会停止读取,因为它没有应用 while 内部的条件。

我在这里做错了什么?

附: tempChar 和 tempToken 都定义为 char 变量。还有一个

【问题讨论】:

  • strcpy(&tempToken[i], &tempChar); strcpy 需要一个以 0 结尾的 char 数组作为源,您正在传递一个 char 的地址,并且知道内存中的内容。
  • 如果你到达 EOF,你的内部循环没有转义测试,你应该使用 && 而不是 ||做你想做的事。此外,根据上述评论者,tempToken[i] = tempChar,而不是 strcpy。
  • 你的意思是&&,而不是||,顺便说一句?
  • 您好,您为什么不阅读完整的文件并将其存储在字符串中,然后使用strtok? cplusplus.com/reference/clibrary/cstring/strtok
  • fgetc() 的返回类型是int,而不是char

标签: c file


【解决方案1】:

我猜这行代码出了点问题:

while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');

由于您使用了||,因此条件始终为真,使其成为无限循环。 试试这个,这可能有效:

while (tempChar != ' ' && tempChar != ':' && tempChar != ';' && tempChar != ',' && tempChar != '\n');

另外,我更喜欢if(feof(asmCode)) 而不是if (tempChar == EOF)。如果 tempChar 的值与 EOF 相同,if (tempChar == EOF) 将不起作用。

【讨论】:

    【解决方案2】:

    正如我在您的代码中看到的,tempchar 的类型是 char:char tempchar

    您不能使用strcpy(&tempToken[i], &tempChar); 来复制字符。 strcpy 将字符串复制到一个字符串缓冲区。

    试试下面的固定代码

    do {
    
        do {
    
            tempChar = fgetc(asmCode);
    
            if (tempChar == EOF)
                break;
            tempToken[i]= tempChar;
    
            i++;
    
        } while (tempChar != ' ' || tempChar != ':' || tempChar != ';' || tempChar != ',' || tempChar != '\n');//reading until the given parameters
        tempToken[i]='0';
        i = 0;  // this will erase the old content of tempToken !!! what are you trying to do here ?
    
        //some other code with some other purpose
    
    } while (tempChar != EOF);//reading until the end of the file
    

    【讨论】:

    • 对您的代码进行了一些额外的更改,我让它工作了。为此非常感谢。但是这次我收到了一个 EXC_BAD_ACCESS 错误 tempToken[i] = tempChar;因为我怀疑检查 EOF 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多