c++ arrays and file reading question
Nov 5, 2010 at 3:15am UTC
I am doing a project and I have to read from a file and input the values into an array. I know how to do this. But now we have to read from a file in put it in multiple arrays. The file that I'm reading looks like this:
4
Assign1 200 95
Assign2 100 80
Project 100 -1
Midterm 100 -1
How would I make it so that the names are put into one array, the 1st numbers in another, and the last numbers in another array?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int readFile(char fileName[])
{
int i = 0;
ifstream input;
input.open(fileName);
while (i != input.eof())
{
input >> grade[i];
i++;
}
input.close();
}
How do I make it so that there are 3 seperate arrays stored instead of just the one grades array
Last edited on Nov 5, 2010 at 3:34am UTC
Nov 5, 2010 at 10:23pm UTC
Sense there is a space, use getline. You can tell it to stop reading at a space so
getline(input, grade[i], ' ');
or am I dead wrong?
edit: just tested it, the getline will work just tell it to stop reading at a space.
so
1 2 3
getline(input, grade[i], ' ' );
getline(input, score[i], ' ' );
getline (input, points[i], '\n' ); // or w/e you want the arrays called..
Last edited on Nov 5, 2010 at 10:37pm UTC
Nov 8, 2010 at 12:43pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
void print(std::string sa[], int len) {
for (int i = 0; i < len; ++i)
std::cout << sa[i] << ' ' ;
std::cout << '\n' ;
}
int main() {
using namespace std;
ifstream fin("data.txt" );
if (!fin) {
cerr << "Open file data.txt failed!\n" ;
return 1;
}
char lines[12] = "" ;
fin.getline(lines, sizeof (lines));
int lineCount = atoi(lines);
// The better way is using vector<string> rather than string arrays.
string* cols1 = new string[lineCount];
string* cols2 = new string[lineCount];
string* cols3 = new string[lineCount];
istringstream iss;
string s;
for (int i = 0; i < lineCount && fin; ++i) {
getline(fin, s);
iss.str(s);
// cout << iss.str() << endl;
iss >> cols1[i] >> cols2[i] >> cols3[i];
// iss.str("");
iss.clear(); // don't forget to do this!
}
// print(cols1, lineCount);
// print(cols2, lineCount);
// print(cols3, lineCount);
// Do something ...
// release cols
delete [] cols1;
delete [] cols2;
delete [] cols3;
fin.close();
}
content of data.txt:
1 2 3 4 5
4
Assign1 200 95
Assign2 100 80
Project 100 -1
Midterm 100 -1
Last edited on Nov 8, 2010 at 1:18pm UTC
Topic archived. No new replies allowed.