【问题标题】:C++ Putting text from a text file into an array as individual charactersC ++将文本文件中的文本作为单个字符放入数组中
【发布时间】:2012-06-03 05:06:59
【问题描述】:

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

目前我有

    #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

【问题讨论】:

  • 您可能想再次查看 C++(尤其是 c)标准库中的各种函数做什么。很可能是因为您误解了类 c 语言中有关字符串或 IO 的某些内容,所以您使这变得比您需要的更难。
  • a std::string 指的是一个字符数组,为什么要把它们放到另一个数组中呢?还有,你fstream的代码写得不好,你是从没用的cplusplus.com上抄过来的吗?
  • Do not loop while good()。 (那个问题标题提到了 eof,但同样的问题在这里:检查是在输入之前)。
  • 好的,谢谢:D

标签: c++ arrays


【解决方案1】:
std::ifstream file("hello.txt");
if (file) {
  std::vector<char> vec(std::istreambuf_iterator<char>(file),
                        (std::istreambuf_iterator<char>()));
} else {
  // ...
}

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

【讨论】:

  • @cristicbz:我认为它实际上并不比 push_back 更有效
  • @cristicbz 我怀疑它是否更有效,更不用说更多了。矢量构造函数是使用相同的循环实现的。
  • char first = vec.at(0); if (first == 'A') {…}
  • 我建议你拿起一个good book
  • 我更喜欢 at 而不是 [] ,因为你不知道文件有多大。也许文件是空的。对空向量执行 [0] 可以根据需要订购披萨。
【解决方案2】:
#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);
  }
}

【讨论】:

    猜你喜欢
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多