For this program I'm trying to get the variables of the structure to include specific lines read from a file. I need "name" to include the move names listed in the file and "count" to include the numbers listed in the file but I have no idea how to do so.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iomanip>
#include <sstream>
struct GMoves {
// char name[50];
// favour std::string: https://cal-linux.com/tutorials/strings.html
std::string name ;
int count = 0 ;
};
// expected format: name on first line, count on the next
bool get_gmoves( std::istream& stm, GMoves& gm ) {
return std::getline( stm, gm.name ) && // read in a full line as the name
stm >> gm.count && // read in count from the next line
stm.ignore( 1000, '\n' ) ; // and extract and discard the new line at the end
}
// vector: https://cal-linux.com/tutorials/vectors.html
std::vector<GMoves> get_gmoves_from_stream( std::istream& stm ) {
std::vector<GMoves> result ;
GMoves gm ;
// add each gmoves read from the stream to the vector
while( get_gmoves( stm, gm ) ) result.push_back(gm) ;
return result ;
}
int main() {
// we use a string stream to test our code
// after testing is done, we would replace this with an actual input file stream
std::istringstream test_file( "Fire Blast\n""6\n""Sword Strike\n""7\n""Mace Smash\n""10\n""Magic Bomb\n""5\n"
);
constauto all_gmoves = get_gmoves_from_stream(test_file) ;
// range based loop: http://www.stroustrup.com/C++11FAQ.html#forfor( const GMoves& gm : all_gmoves ) { // for each item in the vector
std::cout << std::setw(20) << gm.name
<< " -" << std::setw(4) << gm.count << '\n' ;
}
}
// expected format: name on first line, count on the next
std::istream& operator>> ( std::istream& stm, GMoves& gm ) {
std::getline( stm, gm.name ); // read in a full line as the name
stm >> gm.count; // read in count from the next line
stm.ignore( 1000, '\n' ) ; // and extract and discard the new line at the end
return stm;
}
That allows:
1 2 3 4 5 6 7
std::vector<GMoves> get_gmoves_from_stream( std::istream& stm ) {
std::vector<GMoves> result ;
GMoves gm ;
// add each gmoves read from the stream to the vector
while( stm >> gm ) result.push_back(gm) ;
return result ;
}