Need direction with fstream project

Hello, my assignment is to make a program that takes a file as input, reads
the lines, and outputs them in a different format. It's something like:
lastName firstName creditHours inState
lastName firstName creditHours outState
etc. etc. etc;

We are told to make and output file that has
firstName lastName creditHours tuitionCost
etc. etc. etc.

This is what I made this evening but I have no idea how to use the getline()
function when I need to separate the strings like this. I haven't even gotten
to the part of the code where I have to worry about the output file, just clueless about how separate the strings and loop it for the next line.

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

using namespace std;

ifstream Inputfile;
ofstream Outputfile;


int main(){

	string first;
	string last;
	string credits;
	string state;
	string line;
	string blank = " ";

	Inputfile.open("input.dat");

	if(Inputfile.is_open()){
		for(int i = 0; i <= 4; i++){
			do{
				getline(cin, line);

			if(i=1){
				line = first;
			}
			else if(i=2){
				line = last;
			}
			else if(i=3){
				line = credits;
			}
			else{
				line = state;
			}

			}while(!"\n");

		}
	}
When you need to separate inputs, don't use getline because that will (true to it's name) get a single line of text from the stream associated with the istream object.

What you want instead is to use the ">>" operator which stops reading on white space. Note that the implementation of this operator allows one to chain multiple calls. In your case, a way of doing this is:

1
2
while(Inputfile >> last >> first >> credits >> state)
{ /* do something with input read */ }


see:
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
I agree with Smac89 a little...

You could use >> and try to match up the inputs... but that won't help with broken lines (lines with an extra space or not enough spaces could confuse your program).

What you want is called a tokeniser, you could try something like this to tokenise yourself.

1
2
3
4
5
6
7
8
9
10
11
    size_t  endOfLast = line.find_first_of(' ');
    last = (endOfLast != std::string::npos) ? line.substr(0, endOfLast ): "";

    size_t   endOfFirst = line.find_first_of(' ', endOfLastname);
    first = (endOfFirst != std::string::npos) ? line.substr(0, endOfFirst): "";

    size_t     endOfCredits = line.find_first_of(' ', endOfFirst );
    credits = (endOfCredits != std::string::npos) ? line.substr(0, endOfCredits): "";

    size_t   endOfState = line.find_first_of(' ', endOfCredits);
    state = (endOfState != std::string::npos) ? line.substr(0, endOfState): "";


Hope this helps.

Topic archived. No new replies allowed.