如何将以逗号和空格分隔的整数读取到 2D 数组中?

How to read in integers, separated by commas and spaces, into a 2D array?

本文关键字:读取 整数 2D 数组 分隔 空格      更新时间:2023-10-16

我有一个输入文件,如下所示:

3, 2, 5
2, 4, 9
6, 5, 9

我做了一个array[3][3].

我的问题是:如何在跳过空格和逗号的同时将其读入我的数组?

另外:我不能使用stoi(没有C++11(,我还没有涵盖向量。

我已经尝试了下面的代码块,但我生成的数组充满了零。

string sNum;                     // Current number (as string)
int num = 0;                     // Current number (as int)
ifstream inFile;                 // Make input file stream
inFile.open("Numbers.txt");      // Open my input file of 3x3 numbers
while (getline(inFile, sNum, ',')) {                                 // Gets 'line' from infile ..
       // puts it in sNum .. 
       // delimiter is comma (the problem?).
for (int rowCount=0; rowCount<3; rowCount++) {                    // Go through the rows
for (int columnCount=0; columnCount<3; columnCount++) {   // Go through the columns
num = atoi(sNum.c_str());                         // String 'sNum' to int 'num'
array[rowCount][columnCount] = num;               // Put 'num' in array

} // end columnCount for
} // end rowCount for
} // end while

我认为这是在空间中阅读。如何忽略获取整数之间的空格?

这是一个解决方案:

string sNum;                                                                                                                                                                     
int array[3][3];
int num = 0;                                                                                                                                                                        
ifstream inFile;                                                                                                                                                                   
stringstream ss;
inFile.open("Numbers.txt");      // Open the input file of 3x3 numbers                                                                                                                                       
int row = 0;
int col = 0;
while (getline(inFile, sNum)) {  // Gets entire line from inFile and stores in sNum                                                                                                             
ss.str(sNum); //puts the line into a stringstream
while(ss >> num)
{
if(col == 3) //handles our 2D array indexes.
//when col reaches 3, set it back to 0 and increment the row.
{
row++;
col = 0;
}
array[row][col] = num;
col++;
//eliminate any commas and spaces between each number.
while(ss.peek() == ',' || ss.peek() == ' ')
ss.ignore();
}
ss.clear();
} //        end while                                                                                                                                                                                      
}