I'm not sure what you wish to do. Does the std::string line already has the line you wish to read in it? If yes, reading the std::string into the struct should be easy. It should be this: (I'm assuming that by string you meant a std::string)
1 2 3
menuList[i].menuItem = line;
...//Get another line to get the price
menuList[i].menuPrice = stod(line); //stod() converts the input std::string into a double
(But this doesn't make much sence...)
If not, then things get a little more complicated...
Inside the for loop:
1 2 3 4 5 6
char currentLine[256];
inFile.getline(currentLine, 256); //First parameter is the buffer you wish to read into, second the max number of chars to read
menuList[i].menuItem = currentLine;
inFlie.getline(currentLine, 256); //Read a second time to get the price line
line = currentLine;
menuList[i].menuPrice = stod(line); //stod() converts the input std::string into a double
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
struct menu_item
{
std::string name ;
double price = 0 ;
};
int main()
{
const std::string file_name = "Ch9_Ex4Data.txt" ;
// create the test file
{
std::ofstream(file_name) << "Plain Egg\n""1.45\n""Bacon and Egg\n""2.45\n""Muffin\n""0.99\n""French Toast\n""1.99\n""Fruit Basket\n""2.49\n""Cereal\n""0.69\n""Coffee\n""0.50\n""Tea\n""0.75\n" ;
}
const std::size_t MAX_ITEMS = 8 ; // maximum possible number of items
menu_item items[MAX_ITEMS] ;
std::size_t num_items = 0 ; // actual number of items that were read from the file
std::ifstream file(file_name) ; // open the file for input
std::string name_str, price_str ;
// try to read name and price as complete lines, up to a maximum of MAX_ITEMS
while( num_items < MAX_ITEMS && std::getline( file, name_str ) && std::getline( file, price_str ) )
{
try
{
// try to convert the price read in as a string into a number
// http://en.cppreference.com/w/cpp/string/basic_string/stofconstdouble price = std::stod(price_str) ; // may throw if conversion fails
// conversion was successful
items[num_items].name = name_str ;
items[num_items].price = price ;
++num_items ;
}
catch( const std::exception& )
{
// conversion failed
std::cerr << "invalid price for item " << std::quoted(name_str) << ". item was ignored.\n" ;
}
}
std::cout << "the following items were read from the file\n-------------------------\n" ;
for( std::size_t i = 0 ; i < num_items ; ++i )
std::cout << std::setw(15) << std::quoted(items[i].name) << ' ' << items[i].price << '\n' ;
}
I have an array of .menuitem and .menuprice, and I was looking for a way to read the file into the array. I didn't know what to put to read on an entire line since issuing infile >> only went to a white space