C++向txt文本中写入字符串,并进行保存

学习C++ 文件输入和输出内容。
让程序向指定文件写入内容,掌握文件输出类ostream类的使用。
使用此类时,必须在头文件中包含iostream。

   #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    /*   author:温暖wk依然
     题目:向txt文本中写入一个字符串:
    若文件不存在,则新建一个文件;否则,直接输入内容
    */
    int main()
    {
    	ofstream os;     //创建一个文件输出流对象
    	os.open("books.txt");//将对象与文件关联
    	string str;
    	cout<<"向文本中写入以下内容!"<<endl;
    	cin>>str;       
    	os<<str;   //将输入的内容放入txt文件中
    	os.close();
    	return 0;
    }
  • 10
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
您可以使用C++的文件操作和字符串处理来读取txt文本内容并将其写入csv表格。 首先,您需要包含必要的头文件: ```cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> ``` 然后,您可以编写一个函数来读取txt文件内容并将其写入csv表格: ```cpp void convertTxtToCsv(const std::string& txtFilePath, const std::string& csvFilePath) { std::ifstream txtFile(txtFilePath); std::ofstream csvFile(csvFilePath); if (!txtFile.is_open()) { std::cout << "Failed to open txt file!" << std::endl; return; } if (!csvFile.is_open()) { std::cout << "Failed to create csv file!" << std::endl; return; } std::string line; while (std::getline(txtFile, line)) { std::vector<std::string> fields; std::stringstream ss(line); std::string field; // 将line的数据按照分隔符逐个读取到fields while (std::getline(ss, field, ',')) // 根据具体的分隔符修改此处 { fields.push_back(field); } // 将fields的数据按照CSV格式写入csv文件 for (const std::string& field : fields) { csvFile << "\"" << field << "\","; } csvFile << std::endl; } txtFile.close(); csvFile.close(); std::cout << "Conversion completed!" << std::endl; } ``` 在上述代码,`txtFilePath`是要读取的txt文件路径,`csvFilePath`是要生成的csv文件路径。您需要根据实际情况修改分隔符,例如上述代码使用的是逗号作为分隔符。 最后,您可以调用这个函数来进行转换: ```cpp std::string txtFilePath = "path_to_txt_file.txt"; std::string csvFilePath = "path_to_csv_file.csv"; convertTxtToCsv(txtFilePath, csvFilePath); ``` 请将`path_to_txt_file.txt`替换为您要读取的txt文件的实际路径,将`path_to_csv_file.csv`替换为您要生成的csv文件的实际路径。 这样,您就可以使用C++读取txt文本内容并将其写入生成的csv表格了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值