I've been trying to import text from a .txt
file into a 2D array of string, but it doesn't seem to be working. Each row in the .txt
file has three values/elements separated that I need to copy.
This is the code:
// i am only allowed to use these libraries.
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
const int rows = 38;
const int columns = 3;
string companies[rows][columns];
// Inputting file contents
ifstream file;
file.open("companies.txt");
while(!file.eof())
{
for(int i = 0; i < 38; i )
{
for(int j = 0; j < 3; j )
{
getline(file, companies[i][j], ',');
}
}
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < 38; i )
{
for(int j = 0; j < 3; j )
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}
This is the data that I want to import :
Symbol,Company Name,Stock Price
ATRL,Attock Refinery Ltd.,171.54
AVN,Avanceon Ltd. Consolidated,78.1
BAHL,Bank AL-Habib Ltd.,54.97
CHCC,Cherat Cement Company Ltd.,126.26
CodePudding user response:
One of the problems with your code is that you are only looking for ,
as a delimiter and not handling line breaks between the rows at all. Normally, I would suggest reading each row into a std::istringstream
and then use std::getline(',')
to parse each stream, but you say that you are not allowed to use <sstream>
, so you will just have to parse each row manually using std::string::find()
and std::string::substr()
instead.
Also, using while(!file.eof())
is just plain wrong. Not just because it is the wrong way to use eof()
, but also because your for
loops are handling all of the data, so there is really nothing for the while
loop to do.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int max_rows = 38;
const int max_columns = 3;
string companies[max_rows][max_columns];
string line;
string::size_type start, end;
// Inputting file contents
ifstream file("companies.txt");
int rows = 0;
while (rows < max_rows && getline(file, line))
{
start = 0;
for(int j = 0; j < max_columns; j)
{
end = line.find(',', start);
companies[rows][j] = line.substr(start, end-start);
start = end 1;
}
rows;
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < rows; i)
{
for(int j = 0; j < max_columns; j)
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}