将行中的多个整数输入二维数组C++

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

我初始化了一个二维数组,并尝试分别填充该数组。我的问题是我无法更新二维数组。

输入为:

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

我的代码是:

stringstream s(input);

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

扫描输入后需要输入stringstream,所以你的代码应该是

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

这是完整的解决方案加上打印功能:


#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';
    }
}

这会给你这样的结果:

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


希望这就是您所需要的。

请注意,您不必使用数组以二维方式存储信息(如 int 值),因为您还可以使用动态大小的容器,如 std::vector,如下所示。使用 std::vector 优点 是您不必事先知道输入文件中的行数和列数。所以你不必事先为行和列分配内存。您可以动态添加值。下面的程序从 input.txt 读取数据(int 值)并将它们存储在二维 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;
}

上面程序的输出可见here。上面提到的 link.

也给出了读取 int 值的输入文件

如果您想使用 std::cin 而不是 std::ifstream 进行输入,那么您只需将行 while(getline(inputFile, line, '\n')) 更改为 :

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

并删除对 inputFile 的其他引用。 逻辑保持不变。 IMO 从文件中读取可以节省时间和精力,因为用户不必一次又一次地将输入写入控制台。