C++ 使用C+;中的\n个字符进行流到字符串的转换+;
当我的istream还包含换行符并且我不想转义空白时,如何将istream转换为字符串?C++ 使用C+;中的\n个字符进行流到字符串的转换+;,c++,string,type-conversion,istream,C++,String,Type Conversion,Istream,当我的istream还包含换行符并且我不想转义空白时,如何将istream转换为字符串? 谢谢。如果您指的是如何将整个std::istream复制到std::string中,那么有很多方法 这里有一个: int main() { // here is your istream std::ifstream ifs("test.txt"); // copy it to your string std::string s; for(char c; ifs.ge
谢谢。如果您指的是如何将整个
std::istream
复制到std::string
中,那么有很多方法
这里有一个:
int main()
{
// here is your istream
std::ifstream ifs("test.txt");
// copy it to your string
std::string s;
for(char c; ifs.get(c); s += c) {}
// display
std::cout << s << '\n';
}
intmain()
{
//这是你的istream
std::ifstream ifs(“test.txt”);
//将其复制到字符串中
std::字符串s;
对于(char c;ifs.get(c);s+=c){
//展示
std::cout您可以为整个文件分配一个足够大的字符串,然后立即读取:
ifstream fd(filename); // open your stream (here a file stream)
if (!fd)
exit(1);
fd.seekg(0, ios_base::end); // go to end of file
size_t filesize = fd.tellg(); // dtermine size to allocate
fd.seekg(0, ios_base::beg); // go to the begin of your file
string s; // create a new string
s.resize(filesize+1); // reserve enough space to read
fd.read(&s[0], filesize); // read all the file at one
size_t bytes_read = fd.gcount(); // it could be than less bytes are read
s.resize(bytes_read); // adapt size
您可以像这样使用istreambuf\u迭代器
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifile("test.txt"); // open
std::string str(std::istreambuf_iterator<char>(ifile), {}); // initialize
std::cout << str; // display
}
#包括
#包括
#包括
int main()
{
std::ifstream ifile(“test.txt”);//打开
std::string str(std::istreambuf_迭代器(ifile),{});//初始化
std::难道你不想让字符串包含字面字符'\'
和'n'
而不是换行符吗?甚至只是询问“转换”的问题将数据流转换为字符串意味着一种根本性的误解。数据流是数据流,而字符串是字节容器。两者完全不同。您的意思是希望将数据流中的所有字节提取到字符串中,直到数据流耗尽(达到EOF)为止或者什么?具体而精确。未格式化的输入函数?noskipws
?使用istreambuf\u迭代器对其进行初始化?