将 .txt 文件的内容收集为字符串,C++
我目前有一个小程序,它将 .txt 文件的内容重写为字符串。
但是我想将文件的所有内容收集为单个字符串,我该怎么做?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string file_name ;
while (1 == 1){
cout << "Input the directory or name of the file you would like to alter:" << endl;
cin >> file_name ;
ofstream myfile ( file_name.c_str() );
if (myfile.is_open())
{
myfile << "123abc";
myfile.close();
}
else cout << "Unable to open file" << endl;
}
}
I currently have a little program here that will rewrite the contents of a .txt file as a string.
However I'd like to gather all the contents of the file as a single string, how can I go about this?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string file_name ;
while (1 == 1){
cout << "Input the directory or name of the file you would like to alter:" << endl;
cin >> file_name ;
ofstream myfile ( file_name.c_str() );
if (myfile.is_open())
{
myfile << "123abc";
myfile.close();
}
else cout << "Unable to open file" << endl;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您声明一个字符串和一个缓冲区,然后使用 while not EOF 循环读取文件并将缓冲区添加到字符串。
You declare a string and a buffer and then read the file with a while not EOF loop and add buffer to string.
libstdc++ 的家伙有一个 关于如何做的很好的讨论这与
rdbuf
。重要的部分是:
我知道,您询问过将内容放入
string
中。您可以通过将out
设为std::stringstream
来实现这一点。或者您可以使用 < 将其增量添加到std::string
中代码>std::getline:The libstdc++ guys have a good discussion of how to do this with
rdbuf
.The important part is:
I know, you asked about putting the contents into a
string
. You can do that by makingout
astd::stringstream
. Or you can just add it to astd::string
incrementally withstd::getline
:如果您想逐行执行此操作,只需使用字符串向量即可。
If you want to do it line by line, just use a vector of strings.
您还可以迭代并读取文件,同时将每个字符分配给字符串,直到到达 EOF。
这是一个示例:
You can also iterate and read through the file while assigning each character to a string until the EOF is reached.
Here is a sample: