1

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 が 100 回含まれているにもかかわらず、strcmp の戻り値として 1 または -1 が返されます。

何を試すべきですか?

4

1 に答える 1

1

fgets文字列の一部として改行文字を返します。比較対象の文字列には改行が含まれていないため、異なるものとして比較されます。

std::ifstreamC++ で書いているので、ファイルを使用しstd::getlineて読みたいと思うかもしれません。によって返される文字列にgetlineは改行が含まれず、追加のボーナスとして、行サイズの制限を指定する必要はありません。

別の (無関係な) 問題: 使い方while (!foef(file))が間違っているため、最後の行が 2 回読み取られる可能性があります。代わりにfgets、null ポインターが返されるまでループする必要があります。

于 2012-10-21T11:49:35.470 に答える