0

so my input file is this

Target

Inventory:
tech 200 5
food 10 100
clothes 15 10

And i need to be able to record the store name, and its inventory

so far i have this working code

struct item {
    std::string kind;
    int price;
    int quanity;
};

int main(int argc, char **argv){

std::fstream file;

file.open(argv[1]);

if (file.fail()){
    std::cerr << "Error opening file!\n";
    exit(1);
}

std::vector<struct item> inventory;
std::string name;
struct item target;

while(!file.eof()){
    file >> name;

    if(name == "Inventory:"){

        while(file >> target.kind >> target.price >> target.quanity){
            inventory.push_back(target);
        }

        break;
    }

}

for(auto a : inventory){

    std::cout << "Kind: " << a.kind << "\tPrice: " << a.price << "\tQuanity: " << a.quanity << std::endl;

}

so this code works fine, but apparently the text file is suppose to be like this

Target

Inventory:
tech,200,5
food,10,100
clothes,15,10

Now i cant seem to figure out how to get this working when each item is separated by a comma. Please help! Ive tried adding this line inside the second while loop but its no good

if (file.peek() == ','){
                file.ignore();
            }
  • Don't worry too much about parsing a line *while* reading it from a file. Just read the entire line. Now it's "parse a string into three variables". There is a function to split that string based on a character (here a comma) into three strings. You then need to convert two of those strings into ints. – Steve Feb 26 '18 at 06:02
  • 1
    How to do all this can be found in your favorite reference or textbook. – Steve Feb 26 '18 at 06:03
  • There *are* other ways to accomplish this, but this should get you on the right track. – Steve Feb 26 '18 at 06:04
  • 1
    A very similar question. https://stackoverflow.com/questions/48980998/cin-with-spaces-and. – R Sahu Feb 26 '18 at 06:09
  • You can use [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) to parse the first string. – xskxzr Feb 26 '18 at 15:30

0 Answers0