Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Printing from istringstream

$
0
0
Here is what I need to do:

Quote

Exercise 8.11: The program in this section defined its istringstream object inside
the outer while loop. What changes would you need to make if record were defined
outside that loop? Rewrite the program, moving the definition of record outside the
while, and see whether you thought of all the changes that are needed.


struct PersonInfo 
{
	string name;
	vector<string> phones;
};

int main(int argc, char *argv[])
{
	string line, word; 
	vector<PersonInfo> people;
	
	PersonInfo info;
	istringstream record(line);

	while (getline(cin, line)) 
	{
		record >> info.name; 
		
		while (record >> word) 
		{
			info.phones.push_back(word); 
		}

		people.push_back(info); 
	}

	for (auto x : people)
	{
		cout << x.name << endl;
		for (auto a : x.phones)
		{
			cout << a << endl;
		}
	}
}



I works if I keep the istringstream declaration inside the outer while loop.


struct PersonInfo 
{
	string name;
	vector<string> phones;
};

int main(int argc, char *argv[])
{
	string line, word; 
	vector<PersonInfo> people;

	while (getline(cin, line)) 
	{
                PersonInfo info;
	        istringstream record(line);
		record >> info.name; 
		
		while (record >> word) 
		{
			info.phones.push_back(word); 
		}

		people.push_back(info); 
	}

	for (auto x : people)
	{
		cout << x.name << endl;
		for (auto a : x.phones)
		{
			cout << a << endl;
		}
	}
}


Once I place the declarations outside the outer loop, I can only get the contents person to print once, and the rest get a '\n' character.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>