简体   繁体   English

将文件中的所有行存储到字符串数组

[英]Storing all lines from a file to a string array

I have following code to read a text file line by line and store data in a string* variable:我有以下代码逐行读取文本文件并将数据存储在string*变量中:

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

int main(){
    // open a file in read mode.
   ifstream infile; 
   infile.open("iris.csv"); 

    // read file line by line and store here: 
    string *strlist; 
    int count =0; 
    for (string line; getline(infile, line); ) {
        strlist[count] = line; 
        count++; 
    }
    infile.close(); 
    //print all lines: 
    for (int i=0; i<count; i++){
        cout << strlist[i];
    }
}

Will above work or will there be some memory problem.上述工作是否会出现一些 memory 问题。 Do I need to make a new string before assigning a value strlist[i]=line ?在分配值strlist[i]=line之前是否需要创建一个new字符串?

I did not try it fearing that an error may cause data damage.我没有尝试过,担心错误可能导致数据损坏。 Thanks for your help.谢谢你的帮助。

Using vector is a good option.使用矢量是一个不错的选择。

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

int main(){
    // open a file in read mode.
   ifstream infile; 
   infile.open("iris.csv"); 

    // read file line by line and store here: 
    vector<string> strlist; 

    for (string line; getline(infile, line); ) {
    //or
    //while (getline(infile, line)) {
        strlist.push_back(line); 
    }
    infile.close(); 
    //print all lines: 
    for (int i=0; i<strlist.size(); i++){
        cout << strlist[i];
    }
}

I think if you want to load the file all in one time in c++, it must will crush your memory.我想如果你想在 c++ 中一次性加载文件,它一定会粉碎你的 memory。 just read one line and do something on it or make a counter to remember how much you had loaded.After you finish one part then go for next one.只需阅读一行并在其上做一些事情或做一个计数器来记住你加载了多少。完成一个部分后,然后 go 为下一个。

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

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