简体   繁体   English

在C ++中比较字符串

[英]Comparing string in C++

I want to simplify a txt document and I tried this code: 我想简化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;
}

Unfortunately, despite the infile includes word1, word2 and word3 hundred times I still get 1 or -1 as the return value of strcmp. 不幸的是,尽管infile包含word1,word2和word3一百次,但我仍然得到1或-1作为strcmp的返回值。

What should I try? 我应该怎么做?

fgets returns the newline character as part of the string. fgets返回换行符作为字符串的一部分。 Since the strings you are comparing against don't contain a newline, they will be compared as different. 由于您要比较的字符串不包含换行符,因此它们将被比较为不同的字符串。

Since you are writing in C++, you may want to use std::ifstream and std::getline to read the file. 由于您使用C ++编写,因此您可能需要使用std::ifstreamstd::getline来读取文件。 The strings returned by getline will not have the newline in them, and as an added bonus you won't have to specify a limit on the line size. getline返回的字符串中将不会包含换行符,此外,您不必指定行大小的限制,这是一个额外的好处。

Another (unrelated) issue: Using while (!foef(file)) is wrong, and can result in the last line being read twice. 另一个(不相关的)问题:使用while (!foef(file))是错误的,并且可能导致最后一行被读取两次。 Instead, you should loop until fgets returns a null pointer. 相反,您应该循环直到fgets返回空指针。

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

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