My sscanf version went something like this.
Code:
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main()
{
char line[100]; // name of the food
char name[100]; // name of the food
int inCategory; // what kind of food
float inCalories; // calories
float inCarbohydrates; // grams
float inFat; // grams
float inCholesterol; // grams
float inSodium; // grams
float inProtein; // grams
ifstream in("file.txt");
while ( in.getline(line, sizeof line) )
{
if ( sscanf(line, "%99[^~]~%d %f %f %f %f %f %f", name,
&inCategory, &inCalories, &inCarbohydrates, &inFat,
&inCholesterol, &inSodium, &inProtein) == 8 )
{
// ...
// ++counter;
}
}
return 0;
}
If you only increment your loop counter on success, then you don't need to do any decrements.
The stringstream version is fairly similar, and I chose to ditch char arrays for strings as well, much like citizen suggested.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string line;
string name; // name of the food
int inCategory; // what kind of food
float inCalories; // calories
float inCarbohydrates; // grams
float inFat; // grams
float inCholesterol; // grams
float inSodium; // grams
float inProtein; // grams
ifstream file("file.txt");
while ( getline(file, line) )
{
istringstream iss(line);
if ( getline(iss, name, '~') &&
iss >> inCategory >> inCalories >> inCarbohydrates >> inFat
>> inCholesterol >> inSodium >> inProtein )
{
// ...
}
}
return 0;
}