在C ++中比较字符串

时间:2012-10-21 11:41:13

标签: c++ arrays char compare

我想简化一个txt文档,我尝试了这段代码:

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    // 1. Step: Open files
    FILE *infile;
    FILE *outfile;
    char line[256];
    infile = fopen("vcard.txt", "r");
    outfile = fopen("records.txt", "w+");
    if(infile == NULL || outfile == NULL){
         cerr << "Unable to open files" << endl;
         exit(EXIT_FAILURE);
    }

    // 2.Step: Read from the infile and write to the outfile if the line is necessary
    /* Description:
    if the line is "BEGIN:VCARD" or "VERSION:2.1" or "END:VCARD" don't write it in the outfile
    */

    char word1[256] = "BEGIN:VCARD";
    char word2[256] = "VERSION:2.1";
    char word3[256] = "END:VCARD";

    while(!feof(infile)){
        fgets(line, 256, infile);
        if(strcmp(line,word1)!=0 && strcmp(line,word2)!=0 && strcmp(line,word3)!=0){ // If the line is not equal to these three words
          fprintf(outfile, "%s", line); // write that line to the file
        }
    }

    // 3.Step: Close Files
    fclose(infile);
    fclose(outfile);

    getch();
    return 0;
}

不幸的是,尽管infile包括word1,word2和word3一百次,我仍然得到1或-1作为strcmp的返回值。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

fgets返回换行符作为字符串的一部分。由于您要比较的字符串不包含换行符,因此它们将被比较为不同。

由于您使用C ++编写,因此您可能希望使用std::ifstreamstd::getline来读取文件。 getline返回的字符串不会包含换行符,作为额外的奖励,您不必指定行大小的限制。

另一个(无关的)问题:使用while (!foef(file))是错误的,并且可能导致最后一行被读取两次。相反,你应该循环,直到fgets返回一个空指针。