I'm trying to read a text file into a vector of pairs. The text file contains the following: The first line tells, how many strings there are. The second line is an int, telling how many characters there are in the (first) string. And then, the third line contains the string itself. After that, the next "pattern" follows (again with int how many characters and then string itself). For example:
- 2
- 3
- ABC
- 4
- CDEF
My idea was, to read the first line separately (which works fine). Then create pairs for each int and string. The second part, somehow, doesn't work, so I would really appreciate if someone could help me find the mistake.
So here's my code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main(int argc, char *argv[])
{
if (argv[1])
{some code here...}
// arg[2] is formatted in some manner of the example above
if (argv[2])
{
//Declare Variables:
string buffer;
string temporary;
vector <pair <int, string> > patVec;
pair <int, string> patPair;
// Ifstream first txt File = (argv[2]
ifstream ifile2(argv[2]);
// Get first line and store in variable number of Patterns --> This works fine
getline(ifile2, temporary);
int numberOfPatterns = atoi(temporary.c_str());
// Process rest of file
int i;
for (patVec[i=0]; i <= numberOfPatterns - 1; i++)
{
getline(ifile2, buffer);
stringstream strs(buffer);
// Fill up the Vector with pairs
strs >> patPair.first;
strs >> patPair.second;
patVec.push_back(patPair);
}
}
}
So here's the corrected version of the relevant part, works now: Thanks for the hints;)
//Declare Variables
string buffer;
string temporary;
vector <pair <int, string> > patVec;
pair <int, string> patPair;
int plength;
string pCharacters;
// Get first line and store in variable number of Patterns
getline(ifile2, temporary);
int numberOfPatterns = atoi(temporary.c_str());
cout << "The number of Patterns is " << numberOfPatterns << endl;
// Process rest of file
for (int i=0; i <= numberOfPatterns - 1; i++)
{
// stringstream strs(buffer);
// Fill up the Vector with pairs
getline(ifile2, buffer);
stringstream int_reader(buffer);
int_reader >> plength;
getline(ifile2, buffer);
stringstream str_reader(buffer);
str_reader >> pCharacters;
patPair = make_pair (plength, pCharacters);
patVec.push_back(patPair);
cout << "length of pattern " << i << " is " << plength << endl;
cout << " characters are: " << pCharacters << endl;
}
ifile2.close();
}