Need help getting input from a .txt using getline

Beginner here. Taking an online course and my professor didn't give a whole lot of help for this particular assignment

Write a program that will input user information from a file named in.txt and display it on the console. The user information will include the following:

Full Name,

Street Address,

City/State Address,

Phone Number,
Email.


Do this assignment using getline.



I've been on google for the past couple hours and have made little progress. Here is what I have so far:

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () 
{
  string name, address, address2, phone, email;  
  ifstream in;
  in.open("in.txt");
    
  while (in)
  {
  in.getline(name, 2); 
  in.getline(address, 3);
  in.getline(address2, 4);
  in.getline(phone, 5);
  in.getline(email, 6);
  }
  
  in.close("in.txt");
  
  cout << "Name: " << name << endl;
  cout << address << endl;
  cout << address2 << endl;
  cout << "Phone: " << phone << endl;
  cout << "Email: " << email << endl;
  
 return (0); 
}



the contents of in.txt are

1
2
3
4
5
6
Input File Contents
John Smith
321 Golf Club Road
Pleasant Hill, CA 94512
925-685-1230
jsmith@dvc.edu


Really lost here as you can probably tell from the code lol, I have no clue how to approach this. Please help (or at least point me in the right direction)!
Last edited on
Wrong getline. You need a standalone function provided with std::string std::getline( in, name );
http://www.cplusplus.com/reference/string/string/getline/

If the in.txt really has a header line 1 like that, then you have to skip it by reading/ignoring that line first.

The loop.
At start (if) the in is ok, so you start reading. What if any of lines 15-19 fails? You won't get all values of one record. Consider while ( A && B && C && D && E ), where the A-E are the getline invocations.
The && is "lazy", i.e. if the expression one the left is false, then the expression on the right is not evaluated at all.

What is left to do inside the body of the loop? Your five strings now hold one record. On every iteration they are overwritten by the next batch of getlines. Therefore, would you have to copy the values to somewhere before next iteration. To a container: array, list, vector, etc.

Another note: if the file is known to contain exactly one record, then a 'while' is not appropriate.
1
2
3
4
if ( A && B && C && D && E )
{
  // print the values
}
Topic archived. No new replies allowed.