Search code examples
c++arraysstringiostreamifstream

Reading an Input File And Store The Data Into an Array (beginner)!


The Input file:

1 4 red
2 0 blue
3 1 white
4 2 green
5 2 black

what I want to do is take every row and store it into 2D array. for example:

array[0][0] = 1
array[0][1] = 4
array[0][2] = red
array[1][0] = 2
array[1][1] = 0
array[1][2] = blue
etc..

code Iam working on it:

    #include <iostream>
    #include <fstream> 
    #include <string>
    #include <sstream>
    #include <vector>

    using namespace std;

    int convert_str_to_int(const string& str) {
        int val;
        stringstream ss;
        ss << str;
        ss >> val;
        return val;
    }


    string getid(string str){

        istringstream  iss(str);
        string pid;
        iss >> pid;
        return pid;
    }
    string getnumberofcolors(string str){
        istringstream  iss(str);
        string pid,c;
        iss >> pid>>c;
        return c;
    }

    int main() {
        string lineinfile ;
        vector<string> lines;

        ifstream infile("myinputfile.txt"); 
        if ( infile ) {
            while ( getline( infile , lineinfile ) ) {
            lines.push_back(lineinfile);
            }
        }
        //first line - number of items
        int numofitems = convert_str_to_int(lines[0]);

        //lopps items info 
        string ar[numofitems ][3];
        int i = 1;

        while(i<=numofitems ){
            ar[i][0] = getid(lines[i]);
            i++;
        }
        while(i<=numofitems ){
            ar[i][1] = getarrivel(lines[i]);
            i++;
        }

        infile.close( ) ;
        return 0 ;
    }

when I add the second while loop my program stopped working for some reason! is there any other way to to this or a solution to my program to fix it.


Solution

  • It's better to show you how to do it much better:

    #include <fstream> 
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main() {
        ifstream infile("myinputfile.txt");  // Streams skip spaces and line breaks
    
        //first line - number of items
        size_t numofitems;
        infile >> numofitems;
    
        //lopps items info 
        vector<pair<int, pair<int, string>> ar(numofitems); // Or use std::tuple
    
        for(size_t i = 0; i < numofitems; ++i){
            infile >> ar[i].first >> ar[i].second.first >> ar[i].second.second;
        }
    
        // infile.close( ) ; // Not needed -- closed automatically
        return 0 ;
    }
    

    You are probably solving some kind of simple algorithmic task. Take a look at std::pair and std::tuple, which are useful not only as container for two elements, but because of their natural comparison operators.