Archived

This topic is now archived and is closed to further replies.

Small problem with files.

This topic is 5114 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want this program to change the order of the lines in a file randomly. I made a program, but it only works correctly if you have on word per line. For example:
Hello
my
name
is

becomes for example

my
Hello
name
is

but

Hello my
name is

becomes

my
is
name
Hello
 
Here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

int main(int argc, char *argv[])
{
	using namespace std;
	srand(time(0));
	ifstream fin("test.txt");
	vector<string> vec;
	string line;
	while (fin >> line)
	{
		vec.push_back(line);
	}
	fin.close();
	random_shuffle(vec.begin(), vec.end());
	ofstream fout("test.txt");
	fout.clear();
	for (vector<string>::const_iterator it = vec.begin(); it != vec.end(); ++it)
		fout << *it << endl;
	return 0;
}
How do you make it work as planned? I have no clue right now.

Share this post


Link to post
Share on other sites
The >> operator discards white space, which will only grab one word at a time. You should use the getline function, instead. Example:

std::string line;
std::ifstream file(somefile);
std::getline(file,line);


--------
"Hey, what about those baggy pants you kids are wearin' these days? Aren't they hip and cool and poppin' fresh?"-Peter Griffin
"Everytime I see an M followed by a dollar sign I just say "oh god" and go to the next post."-Neurokaotix
the D programming language|google|msdn|XLib reference manual

[edited by - brassfish89 on December 13, 2003 9:34:19 AM]

Share this post


Link to post
Share on other sites