Problems with getting string

Hi, im trying to save and load some text to a file you decide to get the name on. After that you need to add some "secret" text, and then you need to type a word that the pc will find in the document. If i type one word in the secret text it works but it dosent if I type more than one. Heres my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::string filename;

	std::cout << "Enter name for new file: ";
	std::cin >> filename;

	std::ofstream fout(filename.c_str());

	fout << "For your eyes only!\n";
	std::cout << "Enter your secret text: ";
	std::string secret;
	std::cin >> secret;
	fout << "your secret text is: " << secret << std::endl;

	std::cout << "Which word are you looking for? ";
	std::string finding;
	std::cin >> finding;

	fout.close();

	std::ifstream fin(filename.c_str());
	std::cout << "Here are the contents of " << filename << ":\n";
	std::string fileOutput;
	while (!fin.eof())
	{
		std::getline(fin, fileOutput);
		std::cout << fileOutput << std::endl;

		std::size_t found = fileOutput.find(finding);
		if (found != std::string::npos)
			std::cout << "The word '" << finding << "' found at: " << found << std::endl;
	}
	std::cout << "Done\n";
	fin.close();
}
std::cin >> secret; formatted extraction reads space delimited data, i.e. it stops reading at first space.
You might want to use std::getline.

And preliminary answer to the next proble you will have:
http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction
Thanks for the info, however when I tried to fix it with cin.ignore it only showed the first word of what i typed and didnt find the secret word
when I tried to fix it with cin.ignore it only showed the first word of what i typed
Did you use getline in first place?
I had the same order and added it before cin >> finding when should i use getline?
MiiNiPaa wrote:
std::cin >> secret; formatted extraction reads space delimited data, i.e. it stops reading at first space.
If you use >> then it will read only until first whitespace. If you do not want it, then do not use >>. Use something else. Namely std::getline: http://en.cppreference.com/w/cpp/string/basic_string/getline (example at the bottom)

Using ignore without getline is solving a problem you do not have yet.
Thanks for the help
Topic archived. No new replies allowed.