gpt4 book ai didi

C++从命令行读取文本文件...发送带有响应信息的创建.txt

转载 作者:搜寻专家 更新时间:2023-10-31 01:50:59 24 4
gpt4 key购买 nike

抱歉,我是 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;
}

感谢大家..

最佳答案

#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;
}

关于C++从命令行读取文本文件...发送带有响应信息的创建.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com