bahnaynays
bahnaynays

Reputation: 3

Inputting multiple integers from lines into a 2d array c++

I initialized a 2d array and am trying to fill the array respectively. My issue is I cannot get the 2d array to update.

Input is:

0 1 9  
0 4 8  
1 5 5   
2 0 6  
3 2 2  
1 3 1  
2 1 3  
4 3 7  
5 3 4

My code is:

stringstream s(input);

while(count != numV){
    getline(cin, input);
    while(s >> u >> v >> weight)
        Graph[u][v] = weight;
    
    count++;
}

Upvotes: 0

Views: 205

Answers (3)

digito_evo
digito_evo

Reputation: 3682

Here is the full solution plus a print function:


#include <iostream>
#include <iomanip>
#include <sstream>
#include <tuple>


inline static constexpr size_t ROW_COUNT { 7 };
inline static constexpr size_t COL_COUNT { 7 };


void printGraph( int (&graph)[ ROW_COUNT ][ COL_COUNT ], const std::tuple< size_t, size_t >& dimensions, int maxDigitCount );
int getDigitCount( int num );

int main( )
{
    int Graph[ ROW_COUNT ][ COL_COUNT ] { };

    int numV { 9 };
    int count { };
    int maxDigitCount { };

    while( count != numV )
    {
        std::string input;
        std::getline( std::cin, input );
        std::stringstream ss( input );

        int u { };
        int v { };
        int weight { };

        while ( ss >> u >> v >> weight )
        {
            Graph[u][v] = weight;

            if ( getDigitCount( weight ) > maxDigitCount )
            {
                maxDigitCount = getDigitCount( weight );
            }
        }

        ++count;
    }

    constexpr std::tuple< size_t, size_t > dimensions( ROW_COUNT, COL_COUNT );

    printGraph( Graph, dimensions, maxDigitCount );
}

int getDigitCount( int num )
{
    num = abs( num );

    return ( num < 10    ? 1 :
           ( num < 100    ? 2 :
           ( num < 1000    ? 3 :
           ( num < 10'000   ? 4 :
           ( num < 100'000   ? 5 :
           ( num < 1'000'000  ? 6 :
           ( num < 10'000'000  ? 7 :
           ( num < 100'000'000  ? 8 :
           ( num < 1'000'000'000 ? 9 :
                                    10 )))))))));
}

void printGraph( int (&graph)[ ROW_COUNT ][ COL_COUNT ], const std::tuple< size_t, size_t >& dimensions, int maxDigitCount )
{
    std::cout << "\nGraph data:\n" << '\n' << "    \\ Column  ";

    for ( size_t col = 0; col < std::get<1>( dimensions ); ++col )
    {
        std::cout << std::left << std::setw( maxDigitCount + 2 ) << std::setfill(' ') << col;
    }

    std::cout << '\n' << "Row  \\" << '\n' << '\n';

    for ( size_t row = 0; row < std::get<0>( dimensions ); ++row )
    {
        std::cout << " " << row << "            ";

        for ( size_t col = 0; col < std::get<1>( dimensions ); ++col )
        {
            std::cout << std::left << std::setw( maxDigitCount + 2 ) << std::setfill(' ') << graph[ row ][ col ];
        }

        std::cout << '\n' << '\n';
    }
}

This will give you a result like this:

0 1 9
0 4 8
1 5 55
2 0 6
3 2 2
1 3 112
2 1 3
4 3 7832
5 3 4

Graph data:

    \ Column  0     1     2     3     4     5     6
Row  \

 0            0     9     0     0     8     0     0

 1            0     0     0     112   0     55    0

 2            6     3     0     0     0     0     0

 3            0     0     2     0     0     0     0

 4            0     0     0     7832  0     0     0

 5            0     0     0     4     0     0     0

 6            0     0     0     0     0     0     0


Hopefully this is what you need.

Upvotes: 0

Alan
Alan

Reputation: 1

Note that you don't have to use arrays for storing the information(like int values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file. So you don't have to allocate memory beforehand for rows and columns. You can add the values dynamically. The below program read data(int values) from input.txt and store those in a 2D vector.

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
    std::string line;
    int word;

    
    std::ifstream inFile("input.txt");
    
    //create/use a std::vector instead of builit in array 
    std::vector<std::vector<int>> vec;
    
    if(inFile)
    {
        while(getline(inFile, line, '\n'))        
        {
            //create a temporary vector that will contain all the columns
            std::vector<int> tempVec;
            
            
            std::istringstream ss(line);
            
            //read word by word(or int by int) 
            while(ss >> word)
            {
                //std::cout<<"word:"<<word<<std::endl;
                //add the word to the temporary vector 
                tempVec.push_back(word);
            
            }      
            
            //now all the words from the current line has been added to the temporary vector 
            vec.emplace_back(tempVec);
        }    
    }
    
    else 
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }
    
    inFile.close();
    
    //lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
    for(std::vector<int> &newvec: vec)
    {
        for(const int &elem: newvec)
        {
            std::cout<<elem<<" ";
        }
        std::cout<<std::endl;
    }
    
    
    
    return 0;
}

The output of the above program can be seen here. The input file through which int values are read is also given at the above mentioned link.

If you want to take input using std::cin instead of std::ifstream then you just need to change the line while(getline(inputFile, line, '\n')) to :

while(getline(std::cin, line, '\n')) 

And also remove other references to inputFile. The logic remains the same. IMO reading from file saves time and effort since the user don't have to write the inputs again and again into the console.

Upvotes: 0

starboy_jb
starboy_jb

Reputation: 935

You have to make the input stringstream after scanning the input, So your code should be

while(count != numV){
    getline(cin, input);
    stringstream s(input);
    while(s >> u >> v >> weight)
        Graph[u][v] = weight;
    
    count++;
}

Upvotes: 1

Related Questions