Hi there,

I am trying to read values from a .txt file using stringstreams and plan to enter the values into a map,

I am reading into a buffer, but it contains spaces and I believe a character which represent the end of line.

Here is my program so far:

#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
	//I eventually plan to enter the values into a map
	map<string, string> mapname;

	//Ask for the filename to open
	char fileName[20];
	cout << "Enter the name of the .txt file that you would like to open (eg: file.txt) : " << endl;
	cin >> fileName;

	//create the fstream
	ifstream in(fileName);

	//create a stringstream object called buffer
	stringstream buffer;

	//read the file into the buffer
	buffer << in.rdbuf();

	//Now I want to split the buffer so it can be entered into a map, like a phone book

	//close the connection to the .txt file 
	in.close();

	system ("pause");
	return 0;
}

Here is an example of file.txt:

A1 John Doe
A2 John Smith

So I'm trying to put 'A2' into the key part of the map, and 'John Doe' into the mapped part of the map.

I'm trying to do it as simply as possible, just using the standard library.

Really appreciate any advice with this.

Thanks a lot :)

I would take the data from stringstream to a temporary string, maybe 2 temporary strings. After that I could make_pairs out of them and insert them into the map.

Not sure if that is the best option, and in that case the stringstream would not even be necessary. There might be some useful stringstream operators used in parsing the data.

A stringstream is still a stream. Just do it the same way you would with cin:

string key, value;

while ( buffer>> key && getline ( buffer, value ) )
  mapname[key] = value;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.