Read Entire Line from File and Add to String

So this is an easy one I'm sure. I've Googled around and tried some thing but haven't got anywhere so I'm turning to the experts.

I have a file. The file has a word and then a new line and then another word so:
Dog
Cat
House

I want to read a line from that file and add it to a string array so I can read it back later one word at a time. I'm basically creating a dictionary. Hence the name of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Tools::DictionaryInit(wstring DictionaryPath)
{
	{
		ifstream file;
		file.open(DictionaryPath);
		string str;
		while (std::getline(file, str))
		{
			Dictionary.append(str);
			Dictionary.push_back('\n');
		}
		file.close();
	};
};



This is a part of the function where I read back the first 5 words in the string.

1
2
3
4
5
6
7
8
9
std::wcout << "Dictionary Loaded" << std::endl;
			std::wcout << "First 5 dictionary entries:" << std::endl;
			for (int i = 0; i <= 5; i++)
			{
				std::wcout << std::to_wstring(i) << ". " << Dictionary[i] << std::endl;
			}
			std::wcout << "Press any key to continue" << std::endl;
			Console::ReadKey();
			Valid = true;


Currently the program works but it only reads in one letter at a time per line vs the whole line. So the output from the lower function looks like:?
1.D
2.o
3.g
4.C
5.a

Can someone help me clear this up so that I get the whole word?: Thanks
Last edited on
I suspect it has something to do with wide streams.
You are opening the file and reading as ansi-string.
Then you are using wcout with the dictionary.

Make sure the ansi-string is being properly converted to a wide-string while added to the dictionary.

(I hope you're using Linux?)
Last edited on
I'm using Visual Studio 2015 on Windows, sorry to disappoint but I'm solid at a Linux command line so feel free to use Linux CLI terms.

As for the rest I'm still new to C++ so can you explain more?

I could easily change wcout to be cout but I don't see that helping. Maybe an example of what you mean?
Ok, so you're on Windows.

Did you set your command prompt to use the same UTF-16 encoding as your program?

I still don't know anything about how data is read from file into your Dictionary structure.
Figured it out. Thank you everyone for the responses.

1
2
3
4
5
6
7
8
9
10
11
12
13
void Tools::DictionaryInit(wstring DictionaryPath)
{
	{
		ifstream file;
		file.open(DictionaryPath);
		string str;
		while (std::getline(file, str))
		{
			Dictionary.push_back(str);
		}
		file.close();
	};
};
Topic archived. No new replies allowed.