get characters from string

I am having quite a bit of trouble. I can parse a string that I have read from a line of a text file using substr, however, when I want to further extract characters from one component of the parsed string "StudentID" (using another substr) I always get errors.

I have attempted the following to get the last three characters of a 5 digit student ID; NewStudentID=StudentID.substr(2,3). This does not work.

Also, when I output to the screen, the loop appears to continue to run for one or two cycles and outputs blank characters. I don't understand why. Can anyone help me out with this?









#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(int argc, char* argv [])
{
string inputstring;
string line;
ifstream myfile ("W04In.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);

string inputstring (line);

string FirstName,MiddleInitial,LastName,StudentID;
size_t start, end;
start = 0; //initial start value

for (int counter=0;counter<4;counter++)
{
end=inputstring.find_first_of(",", start);
switch(counter)
{
case(0): FirstName=inputstring.substr(start,end);
break;
case(1): MiddleInitial=inputstring.substr(start,end-start);
break;
case(2): LastName=inputstring.substr(start,end-start);
break;
default: StudentID=inputstring.substr(start,end-start);
}
start=end+1;
}

cout << LastName << ", " << FirstName<< ", "<< FirstName <<LastName<<StudentID<<"@student.college.net\n\n";
//pare down StudentID to the last three numbers
//concatonate strings to make email address
//output to file
}

//myfile.close();
}

else cout << "Unable to open file";

system ("pause");
return 0;

}
Topic archived. No new replies allowed.