2

申し訳ありませんが、C ++は初めてで、txtファイルの読み取りと書き込みの基本的な概念を理解できないようです。現在、ユーザーにプロンプ​​トを表示し、データを読み取った後にコマンドラインで出力を配信するプログラムがあります。しかし、私はそれがファイルを読み取ってもらい、その出力でファイルを作成したい

これまでのところここにあります

#include <iostream>
#include <string>

using namespace std;

int main()
{

    cout << "Enter number of names \n";
    int a;
    cin >> a;
    string * namesArray = new string[a];
    for( int i=0; i<a; i++) {
        string temp;
        cin >> temp;
        namesArray[i] = temp;
    }

    for( int j=0; j<a; j++) {
        cout << "hello " << namesArray[j] << "\n";

    }
    return 0;
}

ありがとうございます..

4

3 に答える 3

1

これはファイルの読み取りのサンプル、またはこの例はファイルに書き込んであなたが求めていることを実行します。何をしているのかを知りたい場合は、<<および>>演算子は、ストリームを移動できるウォーターバルブのようなものです。情報を左右に並べると、「cin」はキーボードからの「データジェネレーター」です。ページの例では、「myReadFile.open」は入力ファイルから「データジェネレーター」を作成し、>を使用してそのデータを移動します。 >それを文字列に保存し、<<それをcoutに移動するには、C++ストリームをもう少し理解するのに役立つかどうかわかりません...

于 2013-01-18T05:51:34.190 に答える
1
ifstream input;
input.open("inputfile.txt");
input >> var;  //stores the text in the file to an int or string
input.close();

ofstream output;
output.open("outputfile.txt"); //creates this output file
output << var;  //writes var to the output file
output.close();

それが役立つことを願っています

于 2013-01-18T06:43:01.417 に答える
1
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
    string fileName = "test.txt";        
    //declare a file object
    //options are:
    //ofstream for output
    //ifstream for input
    //fstream for both
    fstream myFile;
    //cannot pass a c++ string as filename so we convert it to a "c string"
    //... by calling strings c_str member function (aka method)
    //the fstream::out part opens the file for writing
    myFile.open(fileName.c_str(), fstream::out);
    //add the text to the file end the line (optional)
    myFile << "Some text" << endl;
    myFile.close();//always close your files (bad things happen otherwise)
    //open the file for reading with fstream::in
    myFile.open(fileName.c_str(), fstream::in);
    string myString;
    //get a line from a file (must be open for reading)
    getline(myFile,myString);
    myFile.close();//always close your file
    //demonstrates that it works
    cout << myString;
}
于 2013-01-18T06:57:06.357 に答える