getline in fstream
Feb 6, 2013 at 7:23pm UTC
my assignment has me taking data from a .txt file and putting it in a program and doing some calculations with it.
the .txt file.
400 25.5 1/4 pound hamburger
400 is the calories, 25.5 is the fat, and 1/4 pound hamburger is the foods name.
my code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include<iostream>
#include<fstream>
#include <string>
#include<iomanip>
using namespace std;
int main()
{
ifstream inFile;
string Food;
float Calories, FatCalories, FatPercent;
inFile.open("C:\\Users\\Kyle\\Documents\\Visual Studio 2012\\Projects\\Homework_7\\food.txt" );
inFile >> Calories;
cout << Calories << endl;
inFile >> FatCalories;
cout << FatCalories << endl;
inFile >> Food;
cout << Food << endl;
im not sure how to make the getline command grab the entire
1/4 pound hamburger from the file and not just the 1/4. Ive tried cin.getline(Food,20) instead of inFile >> Food; but im getting errors from that.
Anyone know what i need to pull the 1/4 pound hamburger into the Food string?
Last edited on Feb 6, 2013 at 7:56pm UTC
Feb 6, 2013 at 7:58pm UTC
After reading
FatCalories
, you could use
std::getline
1 2 3 4 5 6
...
inFile >> FatCalories;
cout << FatCalories << endl;
std::getline(inFile, Food);
You may need to trim the whitespace before reading Food like this:
inFile >> ws;
Last edited on Feb 6, 2013 at 7:58pm UTC
Feb 6, 2013 at 8:13pm UTC
Thanks that was just what i needed!
Topic archived. No new replies allowed.