Multiple words from .dat file

I am trying to read text from a file that includes
lastname firstname bloodpressure
for example:
Jones Tom 110/73

determine whether the blood pressure is normal, above normal, or below normal
and then create a line that reads...

lastname, firstname has normal blood pressure bloodpressure
for example:
Jones, Tom has normal blood pressure 110/73




all I can get is the entire line. I cannot find the correct code to get word for word or int. My code is this...


#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>


using namespace std;

int main() {
string x;
ifstream inFile;

inFile.open("/Users/jennlynn2012/Documents/Programming I/patient.dat");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}

while (inFile >> x) {
cout << x << endl;
}

inFile.close();
}
instead of reading just one item, read all three:
1
2
3
4
5
6
string last_name, first_name, blood_pressure;
...
while (inFile >> last_name >> first_name >> blood_pressure) {
cout <<  last_name << first_name << blood_pressure << endl;
}
...
After opening the file, you can simply assign each part of the .dat file (seperated by empty spaces), to their own variables by using the following code:

1
2
3
4
5
6
7
8
9
10
string Surname, Name, BloodPressure;

inFile.open(patient.dat)

inFile >> Surname;
inFile >> Name;
inFile >> BloodPressure;

cout << Surname << " " << Name << " " << BloodPressure << endl;
...


Then, if you want to read one of the above variables character by character, you can use cin.get() with #include<sstream> :

1
2
3
4
5
6
7
8
9
10
11
string BloodPressurePart1 = "";

cin.get(BloodPressure);                      //This sellects the "1" in "110/73"
BloodPressurePart1 += BloodPressure;

cin.get(BloodPressure);                     //This sellects the second "1" in "110/73"
BloodPressurePart1 += BloodPressure;

cin.get(BloodPressure);                     //This sellects the "0" in "110/73"
BloodPressurePart1 += BloodPressure;
...


BloodPressurePart1 will now be equal to:


110


From here on you can just continue converting BloodPressurePart1 to an integer value.
Last edited on
Topic archived. No new replies allowed.