简体   繁体   English

读到行尾

[英]Reading until end of line

I'm trying to read from a file in C as a part of a project of mine. 我正在尝试从C中的文件读取,这是我的项目的一部分。

My PURPOSE is to parse the words in that file(which are either separated by a whitespace, comma, semicolon or the new line character) into tokens. 我的目的是将文件中的单词(由空格,逗号,分号或换行符分隔)解析为标记。

For that I MUST read character by character. 为此,我必须逐字阅读。

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

Even though the following code reads from the file, it doesn't stop reading since somehow it doesn't apply the conditions inside while. 即使下面的代码从文件中读取,它也不会停止读取,因为它某种程度上不会在while中应用条件。

What am I doing wrong here? 我在这里做错了什么?

PS both tempChar & tempToken are defined as char variables. PS tempChar和tempToken都定义为char变量。 also another 还有另一个

I guess something is going wrong with this line of code: 我猜这行代码出了点问题:

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

Since you used ||, the condition is always true, making it an infinity loop. 由于使用了||,因此条件始终为true,从而使其成为无限循环。 Try this, this may work: 试试这个,这可能起作用:

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

Also, I prefer if(feof(asmCode)) over if (tempChar == EOF) . 另外,我更喜欢if(feof(asmCode))不是if (tempChar == EOF) In case the the value tempChar is same as EOF, if (tempChar == EOF) will not work. 如果值tempChar与EOF相同, if (tempChar == EOF)将不起作用。

as I see in your code the type of tempchar is char: char tempchar 正如我在您的代码中看到的, tempchar的类型为char: char tempchar

you can not use strcpy(&tempToken[i], &tempChar); 您不能使用strcpy(&tempToken[i], &tempChar); to copy char. 复制字符。 the strcpy copy string to a sting buffer. 将strcpy复制字符串到字符串缓冲区。

try the following fixed code 试试下面的固定代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM