简体   繁体   English

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

[英]C++ Putting text from a text file into an array as individual characters

I want to put some text from a text file into an array, but have the text in the array as individual characters. 我想将文本文件中的一些文本放入数组中,但将数组中的文本作为单个字符。 How would I do that? 我该怎么做?

Currently I have 目前我有

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

I'm guessing getline gets one line at a time. 我猜getline一次只能获得一行。 Now how would I split that line into individual characters, and then put those characters in an array? 现在,我该如何将该行分割为单个字符,然后将这些字符放入数组中? I am taking a C++ course for the first time so I'm new, be nice :p 我是第一次上C ++课程,所以我是新手,请好:p

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

Very elegant compared to the manual approach using a loop and push_back. 与使用循环和push_back的手动方法相比,它非常优雅。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM