如何将以逗号和空格分隔的整数读取到 2D 数组中?
How to read in integers, separated by commas and spaces, into a 2D array?
我有一个输入文件,如下所示:
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
}
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 从二进制文件中读取整数数组
- 使用字符串流读取整数并将它们相加
- 如何在从文件中读取整数时使用 file.eof()?
- C++从键盘读取整数的功能
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- 如何从文本文件C++读取整数和特殊字符
- C++ 从控制台读取整数数组
- 从文本文件中读取整数并将它们存储到数组中
- 输入重定向读取整数和char C
- 从文件读取整数到矩阵 (c++)
- 如何读取整数直到线结束
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 从文本文件中读取整数
- 读取整数对,直到文本输入文件中的换行符
- 在C++中从文件中读取整数和字符
- 使用 MFC C++ 6.0 从 ms 访问中读取整数数据
- 从标准输入和输入值中读取整数到向量
- 从文件中读取整数到数组