Skip to main content
Code Review

Return to Revisions

2 of 7
added 289 characters in body
Loki Astari
  • 97.7k
  • 5
  • 126
  • 341

I would create a class and define an input operator:

struct Person
{
 std::string name;
 std::string age;
 std::string salary;
 std::string hoursWorked;
 std::string randomText;
 friend std::istream& operator>>(std::istream& str, Person& data)
 {
 std::string line;
 if (std::getline(str,line))
 {
 stringstream iss(line);
 if ( getline(iss, name, ':') && 
 getline(iss, age, '-') &&
 getline(iss, salary, ',') &&
 getline(iss, hoursWorked, '[') &&
 getline(iss, randomText, ']'))
 { /* OK: All read operations worked */}
 else
 {
 // One operation failed.
 // So set the state on the main stream
 // to indicate failure.
 str.setstate(std::ios::failbit);
 }
 }
 return str;
 }
};

Now your code looks like this:

Person data;
while(readFile >> data)
{
 // Do Stuff
}

PS. I noticed you were using string and ifstream without the std::. This suggests you have using namespace std; in your code. Please don't do that. see Why is "using namespace std;" considered bad practice?

Don't explictly close() a file unless you are going to check that it worked (or are going the re-open). Prefer to let the destructor do the closing (that way it is exception safe). See: My C++ code involving an fstream failed review

Loki Astari
  • 97.7k
  • 5
  • 126
  • 341
default

AltStyle によって変換されたページ (->オリジナル) /