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 回答