代码之家  ›  专栏  ›  技术社区  ›  posop

未格式化的输入到std::string,而不是二进制文件中的c-string

  •  0
  • posop  · 技术社区  · 15 年前

    好的,我用c字串编写了这个程序。我想知道是否有可能读取在块的无格式文本到一个std::字符串?我到处玩弄 if >> 但这一行一行地读。为了使用std::string,我破译了我的代码,把头撞在墙上,所以我想是时候请专家了。这里有一个工作程序,你需要提供一个文件“a.txt”与一些内容,使其运行。

    我试着玩弄:

    in.read (const_cast<char *>(memblock.c_str()), read_size);
    

    std::cout << memblock.c_str() 把它印出来。和 memblock.clear() 没有解开绳子。

    不管怎样,如果你能想出一种使用STL的方法,我将不胜感激。

    这是我用c字符串编写的程序

    // What this program does now:  copies a file to a new location byte by byte
    // What this program is going to do: get small blocks of a file and encrypt them
    #include <fstream>
    #include <iostream>
    #include <string>
    
    int main (int argc, char * argv[]) 
    {
     int read_size = 16;
     int infile_size;
     std::ifstream in;
     std::ofstream out;
     char * memblock;
     int completed = 0;
    
     memblock = new char [read_size];
     in.open ("a.txt", std::ios::in | std::ios::binary | std::ios::ate);
     if (in.is_open())
      infile_size = in.tellg();
     out.open("b.txt", std::ios::out | std::ios::trunc | std::ios::binary);
    
     in.seekg (0, std::ios::beg);// get to beginning of file
    
     while(!in.eof())
     {
      completed = completed + read_size;
      if(completed < infile_size)
      {
       in.read (memblock, read_size);
       out.write (memblock, read_size);
      } // end if
      else // last run
      {
       delete[] memblock;
       memblock = new char [infile_size % read_size];
       in.read (memblock, infile_size % read_size + 1);
       out.write (memblock, infile_size % read_size );
      } // end else
     } // end while
    } // main
    

    如果你看到任何可以使这个代码更好的东西,请随时告诉我。

    1 回复  |  直到 15 年前
        1
  •  4
  •   James McNellis    15 年前

    而不是使用 std::string ,考虑使用 std::vector<char> ;这样你就可以解决所有的问题 const_cast 打电话的结果 std::string::c_str() . 在开始使用之前,只需将向量调整为所需的大小。

    如果要打印内容,可以将空终止符推到后面,以空终止向量的内容:

    std::vector<char> v;
    v.push_back('\0');
    std::cout << &v[0];
    

    或者你可以把它转换成 标准::字符串 :

    std::vector<char> v;
    std::string s(v.begin(), v.end());
    

    这一切都假设您有一些文本块,您想从一个二进制文件读取。如果你想打印出二进制字符,这显然是行不通的。你的问题不太清楚。