user2073188
user2073188

Reputation: 1

Parsing File I/O

I writing a C++ program that needs to be able to read from a .txt file, and parse the input in order to be able to get commands and arguments from each line.

Say I have Animals.txt

A cat1 3
A dog1 4
A cat2 1
D cat1

I want to be able to take this file, and then create a set of if statements for the first letter, so that I can call a function in the main class that corresponds to the first letter, and pass the rest of the line in as arguments.

An exmaple of what i'm trying to do:

if(line[0].compare("A")==0){
    add(line[1],line[2]);
}
if(line[0].compare("D")==0){
    delete(line[1])
}

I've tried to use strtok and the stringstream classes, but either I dont know how to implement the for my needs or they do not work for my needs as values are being put in line[0] that are not at the beginning of the lines of the text file. Any help would be much appreciated.

Upvotes: 0

Views: 405

Answers (2)

Pete Becker
Pete Becker

Reputation: 76428

Create a istringstream object to split each line:

std::istringstream line(my_line);
std::string line0;
std::string line1;
std::string line2;

line >> token;
if (line0 == "A") {
    line >> line1 >> line2;
    add(line1, line2);
} else if (line0 == "D") {
    line >> line1;
    remove(line1);
}

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

First you need std::ifstream to open the file. Then you need std::getline to extract lines from the file:

std::ifstream file("Animals.txt");
std::string line;
while (std::getline(file, line)) {
  // ...
}

Then inside the while loop, stick the line in a std::stringstream and extract the values you need:

std::stringstream ss(line);
char letter;
ss >> letter;
// And so on...

For a char you can do simple == comparison in your if statements:

if (letter == 'A') {
  // ...
}

If you extract the letter into a std::string, just make sure you compare against "A".

I'll let you plug it all together and figure out the rest.

Upvotes: 1

Related Questions