#include <iostream>
#include <iomanip>
#include <math.h>
#include <string>
#include <fstream>
#include <sstream>
 
using namespace std;
 
 
int main()
{
	// Open file to read
	cout << "What file do you want to read?";
	string filelocation;
	getline(cin, filelocation); // Important to use getline here, there may be blanks in the file name
	// Also remove "s, windows adds them in some cases
	if (filelocation.substr(0, 1) == "\"") {
		filelocation = filelocation.substr(1, filelocation.length() - 2);
	}
	string firstname, lastname, line;
	int accountnum;
	double balance;
 
	cout << "FYI, reading from" << filelocation << endl;
	ifstream myfile(filelocation); // Open the file at the location the user asks for
	if (myfile.is_open()) // If it worked write out the values
	{
 
		while (!myfile.eof()) {
			getline(myfile, line);
			cout << line << endl;
			istringstream tempstream(line);
			if (tempstream >> firstname >> lastname >> accountnum >> balance) {
				cout << firstname << lastname << accountnum << balance << endl;
			}
			else {
				cout << "bad line:" << line << endl;
			}
		}
 
		myfile.close();
	}
	else {
		// If the file open didnt work, print out an error
		cout << "Unable to open file";
	}
	system("pause");
	return 0;
}
cs-142/reading-with-string-streams.txt · Last modified: 2015/11/18 22:37 by kseppi
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0