-1

I am trying to pull out the firstName string, However I'm getting very strange outputs.

Sample Data: 75428 Marston, Edward

Wanted Output: Marston Edward 75428

Output Receiving: Marston, Edwa Edward 75428

Code:

ifstream textFile("NameZip.txt");//File initializer

int counter = 0; //Used to cycle data into struct[] implementData. Avoiding a longer more memory hungry alternative since we know the file is going to be 20 lines long
int tmpZip;
string tmpString;

personData implementData[20];//creates object for structure

if(textFile.is_open())//checks to make sure file exists in same folder to avoid errors
{while(getline(textFile,tmpString))
{
    stringstream convert(tmpString.substr(0,6));
    convert >> tmpZip; //pulls out the Zipcode
    string firstName = tmpString.substr(tmpString.find(" ") +1,tmpString.find(","));//pulls out the first name
    string lastName = tmpString.substr(tmpString.find(",")+2); //pulls out last name
    implementData[counter++] = {tmpZip,firstName,lastName}; //sets value for that tab in the structure personData

}}else
    cout << "There was a problem reading from the textFile\nPlease make sure the file is in the same folder as the .cpp program" << endl;
printData(implementData);
return 0;

It's not just this one data to, all data for First Name seems to stop at the 13th character instead of stopping at the comma. Am I splitting the data incorrectly?

2 Answers2

1

Use of boost Spirit :

#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <iostream>
#include <string>
#include <vector>


int main(int argc, char** argv)
{
   std::string const str{"75428 Marston, Edward"};
   std::tuple<int, std::string, std::string> data;

   using namespace boost::spirit::x3;

   auto beg = std::begin(str), end(std::end(str));
   auto ret = parse(beg, end, int_ >> ' ' >> +~char_(',') >> ", " >> +char_ >> (eol | eoi), data);

   if(ret && (beg==end) )
    std::cout << "Parse done : " << std::get<0>(data) << " " << std::get<1>(data) << " " << std::get<2>(data) << "\n";
    else
    std::cout << "Parse failed : '" << std::string(beg, std::next(beg, 5) ) << "'\n";




    return 0;
}
Roby
  • 2,011
  • 4
  • 28
  • 55
1

You have an error in extracting the first name. You are using:

string firstName = tmpString.substr(tmpString.find(" ") +1,tmpString.find(","));

The second argument is not correct. The second argument is meant to be the count -- the number of characters to extract. It is not meant to be the end position. See the documentation.

Change that line to:

auto start = tmpString.find(" ") + 1;
auto end = tmpString.find(",");
string firstName = tmpString.substr(start, (end-start));
R Sahu
  • 204,454
  • 14
  • 159
  • 270