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

时间:2012-05-24 22:34:26

标签: 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;
}

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

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:3)

#include <vector>
#include <fstream>

int main() {
  std::vector< char > myvector;
  std::ifstream myfile("maze.txt");

  char c;

  while(myfile.get(c)) {
    myvector.push_back(c);
  }
}