I am required to pass a textfile that contains comma separated integers into a 2D array in c++. eg if the textfile looks like:
2,3,56,4
3,5,7,1
0,23,9,87
2,4,5,2
I need to put this into a 2D array so that I may later perform calculations (which I do know how to do). I have the following code, but I am struggling very much. Any help would be appreciated. Thank you.
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
const int row =4;
const int col =4;
int array[row][col];
int r =0;
int c =0;
ifstream inputfile("numbers.txt");
if (!inputfile.is_open())
{
cout<<"error"<<endl;
}
string line,num;
int number;
while(get line(inputfile,line))
{
string stream ss(line);
getline(ss,num,',');
number = stoi(num);
for (int r=0; r<row;r++)
{
for (int c=0; c<col; c++)
{
array[row][col] =number;
}
}
inputfile.close();
return 0;
}
Here is a simple example:
static const int MAX_ROWS = 4;
static const int MAX_COLUMNS] = 4;
int matrix[MAX_ROWS][MAX_COLUMNS];
//...
for (int row = 0; row < MAX_ROWS; ++ row)
{
std::string row_text;
std::getline(inputfile, row_text);
std::istringstream row_stream(row_text);
for (int column = 0; column < MAX_COLUMNS; ++column)
{
int number;
char delimiter;
row_stream >> number >> delimiter;
matrix[row][column] = number;
}
}
The above assumes that the text file contains the exact quantity of numbers.
Since the separators differ at the end of a line, each line is read as a string, then use std::istringstream
to treat the stream as a file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.