我有一个看起来像这样的输入文件:
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; // Current number (as string)
int array[3][3];
int num = 0; // Current number (as int)
ifstream inFile; // Make input file stream
stringstream ss;
inFile.open("Numbers.txt"); // Open my input file of 3x3 numbers
int row = 0;
int col = 0;
while (getline(inFile, sNum)) { // Gets 'line' from infile ..
ss.str(sNum);
while(ss >> num)
{
if(col == 3)
{
row++;
col = 0;
}
cout << num << " ";;
array[row][col] = num;
col++;
while(ss.peek() == ',' || ss.peek() == ' ')
ss.ignore();
}
ss.clear();
} // end while
}
删除两个for循环,它们不是必需的。试试这个:
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
int rowCount = 0;
int columnCount = 0;
while (getline(inFile, sNum, ',')) { // Gets 'line' from infile ..
num = atoi(sNum.c_str()); // String 'sNum' to int 'num'
iArray[rowCount][columnCount] = num; // Put 'num' in array
columnCount += 1; if (columnCount > 2) { columnCount = 0; rowCount += 1; }
} // end while
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << iArray[i][j];
}
cout << '\n';
}