【问题标题】:I want to get file content and put each line in item of array我想获取文件内容并将每一行放入数组项中
【发布时间】:2013-07-29 00:30:51
【问题描述】:

我有一个文本文件,该文件包含以下内容:

文件内容

27013.
Jake lexon.
8 Gozell St.
25/7/2013.
0.

我想将文件的内容保存到数组中,每一行保存在数组项中,如:
理论上

new array;
array[item1] = 27013.
array[item2] = Jake lexon.
array[item3] = 8 Gozell St.
array[item4] = 25/7/2013.
array[item5] = 0.

我尝试了很多,但都失败了。

编辑

使用c风格数组的原因是,因为我想熟悉c-style arrayvector这两种方式,而不是简单的方式只有vector

编辑 2

首先调试器没有给我任何错误。 这是我使用的代码。

fstream fs("accounts/27013.txt", ios::in);
if(fs != NULL){
    char *str[100];
    str[0] = new char[100];
    int i = 0;
    while(fs.getline(str[i],100))
    {
        i++;
        str[i] = new char[100];
        cout << str[i];
    }
    cin.ignore();
} else {
    cout << "Error.";
}

以及该代码的结果:

【问题讨论】:

    标签: c++ file


    【解决方案1】:

    方法很简单:

    // container
    vector<string> array;
    
    // read file line by line and for each line (std::string)
    string line;
    while (getline(file, line))
    {
       array.push_back(line);
    }
    
    // that's it
    

    【讨论】:

      【解决方案2】:

      您可以使用std::getline 将每一行读入stringsvector

      #include <fstream>
      #include <vector>
      #include <string>
      
      std::ifstream the_file("the_file_name.txt");
      
      std::string s;
      std::vector<std::string> lines;
      while (std::getline(the_file, s))
      {
          lines.push_back(s);
      }
      

      【讨论】:

      • 是否可以使用不带矢量的 c 样式 char array[] 来做到这一点?
      • @LionKing 这是可能的,但要成为一个可行的解决方案实在是太痛苦了。
      • 我知道我打扰了你,但请原谅我,如果可以的话,你能告诉我一个使用 c 风格的例子吗char array[]
      • @LionKing 您需要一个char 数组的数组,并且您必须事先知道文件中有多少行。您还需要知道每行的长度。真的不值得。
      【解决方案3】:

      当您需要一个没有向量的解决方案时。(我一点也不喜欢)

      #include<iostream>
      #include<fstream>
      using namespace std;
      int main()
      {
          fstream fs;
          fs.open("abc.txt",ios::in);
          char *str[100];
          str[0] = new char[100];
          int i = 0;
          while(fs.getline(str[i],100))
          {
              i++;
              str[i] = new char[100];
          }
          cin.ignore();
          return 0;
      }
      

      注意:假设每行不超过 100 个字符(包括换行符),并且您的行数不超过 100 行。

      【讨论】:

      • 感谢您的帮助,我正在尝试打印任何数组项,但不想要。请问如何打印数组的项目?
      • @LionKing 你坚持使用数组的解决方案,我坚持认为这是一个糟糕的解决方案,有一天会在你的脸上炸开。如果您有充分的理由要求使用纯数组,则应在问题中对其进行说明。
      • @juanchopanza 很糟糕,你是指方法还是我的解决方案?
      • 他的任何缺陷都应该与普通数组一起使用吗??
      • @Saksham 我指的是 OP 坚持使用脆弱的解决方案来解决具有强大、琐碎解决方案的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多