【问题标题】:Istream to string conversion with \n characters in C++在 C++ 中使用 \n 字符将 Istream 转换为字符串
【发布时间】:2015-06-26 08:05:57
【问题描述】:

当我的 istream 还包含换行符并且我不想转义空格时,如何将 istream 转换为字符串? 谢谢。

【问题讨论】:

  • 您的意思是您希望字符串包含文字字符'\''n' 而不是换行符?
  • 即使只是询问将流“转换”为字符串的问题,也表明存在根本性的误解。流是数据流,而字符串是字节容器。两者完全不同。您的意思是您希望将流中的所有字节提取到一个字符串中,直到流干涸(达到 EOF)?要不然是啥?具体而准确。
  • 未格式化的输入函数? noskipws?用istreambuf_iterator<char>s 初始化它?

标签: c++ string type-conversion istream


【解决方案1】:

如果您的意思是如何将整个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';
}

【讨论】:

    【解决方案2】:

    您可以为整个文件分配一个足够大的字符串并立即读取它:

    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
    

    【讨论】:

      【解决方案3】:

      您可以使用istreambuf_iterator 喜欢

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-24
        • 1970-01-01
        • 2014-05-02
        • 2020-02-20
        • 1970-01-01
        • 2013-12-05
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多