1

ユーザー入力からデータを収集して txt ファイルに保存する簡単なプログラムを作成したいと考えています。データを収集して保存する方法はいくつか見つかりましたが、ユーザー入力から異なるインスタンスを txt ファイルの同じ行に書き込む方法が見つかりませんでした。これが私のコードです:

#include <iostream>
#include <fstream>
using namespace std;

int main () {

    char book[30];
    char author[30];
    char quote[64];

  ofstream myfile;
  myfile.open ("myfile.txt", ios::in | ios::ate);

    if (myfile.is_open())
  {
    cout << "Enter the name of the Book: ";  
    fgets(book, 30, stdin);

    cout << "Enter the name of the Author: ";
    fgets(author, 30, stdin);

    cout << "Type the quote: ";
    fgets(quote, 64, stdin);

    myfile << ("%s;",book) << ("%s;",author) << ("%s;",quote);

    myfile.close();
    }

  else cout << "Unable to open file";


  return 0;
}

ファイルへの出力は次のとおりです。

Book01
Author01
"This is the quote!"

私は同じ行になりたいです:

Book01; Author01; "This is the quote!"

助けてくれてありがとう!

4

2 に答える 2

1

このfgets関数はバッファーに改行文字を含めるため、それらを書き込むと、それらの改行はmyfile. 次のような方法で改行を簡単に削除できます。

book[strlen(book)-1] = '\0';

しかし、との混合fgetscout最初は少し奇妙ですので、それを取り除き、cin代わりに使用してください. 例えば:

cin >> book;
于 2013-10-22T23:29:10.773 に答える
0

fgets ドキュメントから: http://www.cplusplus.com/reference/cstdio/fgets/

改行文字は fgets の読み取りを停止させますが、関数によって有効な文字と見なされ、str にコピーされる文字列に含まれます。

そのため、読み取ったデータの最後に \n があります。

于 2013-10-22T23:26:51.250 に答える