-1

I want to read a text file which looks like below and put all those string into an array line by line to manipulate elements later use. How can I do that ?

  TS1 24 12 apple
  TS2 24 15 strawberry banana kiwi

if everything is okay, I want to access looks like

 str_arr1[0] = TS1, str_arr1[2] = 12
 s_array2[0] = TS2, s_array2[5] = kiwi 
  • You are using the terms a bit wrong, an array has a fixed size, in the title you also speak of a vector. https://en.cppreference.com/w/cpp/container/vector https://en.cppreference.com/w/cpp/string/basic_string/getline ...but you should be helped. Also see https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c – Wolfgang May 18 '20 at 11:45

1 Answers1

1

Assuming you mean what you say in the title vector of string and not array (fixed size), you can do this by using file stream ifstream and string stream.

#include <fstream>
#include <sstream>
#include <string>


std::ifstream input_file;
    input_file.open("text_file.txt");
    std::string line;
    std::vector<std::string> output_vector;
    while (getline(input_file, line))
    {
        std::istringstream ss_line(line);
        while(ss_line){
            std::string element;
            ss_line >> element;
            output_vector.push_back(element);
        }
    }

If you want a separate vector for each line, you can use an vector of vectors of strings instead, or if you know the amount of lines the file have, just declare that amount of vectors of strings.

DannyBoi
  • 73
  • 6