I managed to import data from a single dimension array and , after much hassle worked out well. However now I need to do the same with a 2d array, and AGAIN I already spent two days trying to figure out a solution.
What I have for now is the array in a txt file "rates.txt".
2;5
3;7
5;10
7;20
14;20
13;12
So the delimiter is the ";", there are 2 rows and 6 lines. So the 2d array size is defined as follows:
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
int i=0,j=0;
string line;
string array[6][2];
ifstream ratesfile("C:\\rates.txt");
if (ratesfile.is_open()) printf("File Open\n"); else printf("File not open\n");
cin.get();
while (! ratesfile.eof()){
getline(ratesfile,line,';');
array[i][j]=line;
cout << array[i][0]<< endl; //<-- All results are stored here
cout << array[i][1]<< endl; //<-- There are no results stored here :(
i++;}
cin.get();
return 0;
}
#include <curses.h>
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
int i=0,j=0;
string line;
string array[6][2];
ifstream ratesfile("C:\\Documents and Settings\\wboustany.SOCO\\Bureau\\analyser\\rates.txt");
if (ratesfile.is_open()) printf("File Open\n"); else printf("File not open\n");
while (! ratesfile.eof()) {
for(int i = 0; i < 5; ++i) {
for(int j = 0; j < 1; ++j) {
getline(ratesfile,line,';');
array[i][j]=line;
cout << array[i][j]<< endl; }}} // works ok although it prints the last number of the array several times (the number 12).
cin.get();
for(int i = 0; i < 6; ++i)
{
cout << array[i][0]<< endl;
cout << array[i][1]<< endl; } //Doesn't give the requested data, why ?
cin.get();
for(int i = 0; i < 6; ++i) {
for(int j = 0; j < 2; ++j) {
cout << array[i][j]<< endl; }} //Doesn't give the requested data, why ?
ratesfile.close();
cin.get();
return 0;
}
So basically, when I request data from an array outside the "while" loop, I dont get the data I am expecting,
for(int i = 0; i < 5; ++i) {
for(int j = 0; j < 1; ++j)
Change it for:
1 2
for(int i = 0; i < 6; ++i) {
for(int j = 0; j < 2; ++j)
In addition, u told that there's 6 rows and 2 columns in your file, so you don't have to use while anymore. It's good when you don't know how long file is.
In the end, you declared two variables 'i' and 'j' in the beginning. You don't have to make new in for loops. All you've got to do is:
Yes, you're right. getline() function extracts characters from 'ratesfile' to 'line' until it find delimitation character which is ';' in this case. Also it stops if the end of file is reached. Default delimitation character is newline character ('\n').