Reading in first and last name from a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
#include <iomanip>

using namespace std;

const double PI = 3.1416;

int main ()
{
     ifstream inFile;
     ofstream outFile;

     double length;
     double width;
     double area;
     double perimeter;
     double radius;
     double circumference;
     double diameter;
     double beginningBalance;
     double interestRate;
     double endBalance;
     int age;
     string name;

     cout << fixed << showpoint << setprecision(2);


     inFile.open("inData.txt");	//CHANGE PATH FOR YOUR STORAGE DEVICE
     outFile.open("outData.txt");     //CHANGE PATH FOR YOUR STORAGE DEVICE

     outFile << "This program has been written by  " << "\n" << endl;

     inFile >> length;
     inFile >> width;
     inFile >> radius;
     getline(inFile, name);
     inFile >> age;
     inFile >> beginningBalance;
     inFile >> interestRate;

     area = length * width;
     perimeter = (length * 2) + (width * 2);
     area = PI * (radius * radius);
     diameter = 2 * radius;
     circumference = PI * diameter;


     cout << "Rectangle: " << endl;
     cout << "Length = " << length << ", width = " << width << ", area = " <<         area << ", perimeter = " << perimeter << endl;
     cout << "\nCircle: " << endl;
     cout << "Radius = " << radius << ", area = " << area << ", circumference = " << circumference << endl;
     cout << "\nName: " << name << ", age: " << age << endl;


The file I am trying to read a name and age from a file. It is on the third line everything before it is fine.

10.20 5.35
15.6
Randy Gill 31
18500 3.5
A
Last edited on
getline(inFile, name);
will read in everything on the 4th line. Which is Randy Gill 31

Then, 18500 will be read in as age.
3.5 as beginning balance

And the letter A as interest rate, except that interest rate is a double, nota char, so this has all gone very wrong.
Ok, I changed it to:

 
inFile >> name;


Now it outputs Randy
Last edited on
Well then you've got to start thinking. That's what programming is. Thinking about how to solve problems. How about you read in the two names separately, and then join them together?

1
2
3
inFile >> firstName; // Randy
inFile >> secondName;
name =firstName + " " +  secondName; 

Topic archived. No new replies allowed.