Sign in to follow this  
namingway

problem writing text to a file in C++

Recommended Posts

namingway    114
This is my first attempt at making a simple textpad in the console with 5 lines. The problem is whenever there's a space it places the following text on a newline in the text.txt file. also it won't allow for 5 lines if spaces are used sometimes only 1 line dpending.
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::ofstream file;
	std::string word;
	file.open("text.txt", std::ios::app);

	for(int i = 0; i < 5; i++)
	{
		std::cin >> word;
		file << word << "\n";
	}
	file.close();
	return 0;
}

How can I fix that?

Share this post


Link to post
Share on other sites
Durfy    109
I'm not positive but you could strip out the spacing? Even a space has an ASCII code doesn't it? Remove the space from each string then store it?
-durfy

Share this post


Link to post
Share on other sites
namingway    114
I need the spacing stored as well. It stores in the text file like this;
--
text
text
text
text
text
--
and if the newline \n is taken away it prints out like this
--
texttexttexttexttext
--

Share this post


Link to post
Share on other sites
nobodynews    3126
cin only gets one word at a time even if you entered more than one word. If you want to retrieve an entire line at once you must use getline:
std::string input;
std::getline(cin, input);

Share this post


Link to post
Share on other sites
cshowe    360
I'm a bit confused by your question phrasing.

The stream extraction operator >> by default splits on whitespace. You show awareness of this by calling the variable you write to 'word' recognizing that it represents a word not a full line. If you are trying to read data from the stream a full line at a time you'll need to use the getline function

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this