David Ling
David Ling

Reputation: 145

C++ read from a text file and seperate it into variables

This is a block of code from a program im currently writing

//declaration of builder variables
std::string name;
int ability;
int variability;

std::vector<string> builderVector;


std::ifstream buildersList("Builders.txt");
std::string outputFile = "output.txt";
std::string input;

void readFile() //function to read Builders file
{

   std::string line;

// read each line for builders
while (std::getline(buildersList, line)) {

    std::string token;
    std::istringstream ss(line);

    // then read each element by delimiter
    while (std::getline(ss, token, ':')) //spilt the variables 

      ss >> name >> ability >>  variability; 
      builderVector.push_back(token);
      cout << name;

}

And this is my text file

Reliable Rover:70:1.
Sloppy Simon:20:4.
Technical Tom:90:3.

By the use of a dilimiter it returns the following

70:1.20:4.90:3

So far the program successfully reads a text file "Builders.txt" and with a dilimiter, splits at the fulltop to differentiate between each record and stores it in a vector . What im trying to do right now is assign each element thats seperated by a colon to a variable. So for example, Reliable Rover is the name 70 is the ability and 1 is the variability. In my code above i have attempted this through the line

ss >> name >> ability >>  variability; 

But when i go to return a value using cout it only only returns the ability and variaiblity

Thankyou.

Upvotes: 0

Views: 979

Answers (1)

melk
melk

Reputation: 530

You should use your outer loop to read a line, and your inner loop to split it using your delimiter.
Right now, your inner loop just removes the '.' at the end of each line.
Try something along the lines of:

while (std::getline(buildersList, line)) {
    line.pop_back();//removing '.' at end of line
    std::string token;
    std::istringstream ss(line);

    // then read each element by delimiter
    int counter = 0;//number of elements you read
    while (std::getline(ss, token, ':')) {//spilt into different records
      switch (counter) {//put into appropriate value-field according to element-count
      case 0:
        name = token;
        break;
      case 1:
        ability = stoi(token);
        break;
      case 2:
        variability = stoi(token);
        break;
      default:
        break;
      }
      counter++;//increasing counter
    }
    cout << name<<" "<<ability<<" "<<variability<<"\n";

}

Add error-checking as needed (e.g. for stoi)

Upvotes: 2

Related Questions