Structs, command line, & I/O

Hello everyone.
I wasn't sure how to do my recent assignment. It involved taking two (technically 3) command line arguments that are text documents that can have different names, but the file is structured the same no matter the way they are named. With that, you are supposed to make a dynamic array that assigns the contents of the file that have different types, such as strings, ints, and floats.
I don't know how you would add the contents of the text file to an array then print it out.

Reading from file is no different from reading from std::cin.

You can define a struct that can store data of one entry:
1
2
3
4
struct Sample {
  std::string word;
  double number;
};

For convenience, you can put the "read data for one entry" into a function:
1
2
3
4
std::istream& operator>> ( istream& in, Sample& entry ) {
  in >> entry.word >> entry.number;
  return in;
}

Now we can write:
1
2
3
4
Sample data;
while ( std::cin >> data ) {
  // use the entry
}



Dynamic array:
1
2
3
4
5
6
std::vector<int> data;
int entry;
while ( infile >> entry ) {
  data.emplace_back( entry );
}
// use data 
Topic archived. No new replies allowed.