C++将文本文本中的文本作为单个字符放入数组中

for*_*win 0 c++ arrays

我想将文本文件中的一些文本放入数组中,但将数组中的文本作为单个字符.我该怎么办?

目前我有

    #include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
  string line;
  ifstream myfile ("maze.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      // --------------------------------------
      string s(line);
      istringstream iss(s);

    do
    {
        string sub;
        iss >> sub;
        cout << "Substring: " << sub << endl;
    } while (iss);
// ---------------------------------------------
    }
    myfile.close();
  }
  else cout << "Unable to open file"; 
  system ("pause");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我猜getline一次得到一行.现在,我将如何将该行拆分为单个字符,然后将这些字符放入数组中?我是第一次参加C++课程,所以我是新人,很高兴:p

小智 8

std::ifstream file("hello.txt");
if (file) {
  std::vector<char> vec(std::istreambuf_iterator<char>(file),
                        (std::istreambuf_iterator<char>()));
} else {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

与使用循环和push_back的手动方法相比,非常优雅.

  • @cristicbz:我认为它实际上并不比push_back更有效 (4认同)