CMD Text to Text file

i am haveing a problem with the text in the file im not sure if there is anyway to get around it, please tell me if u have any ideas.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
	string sentence;
	fstream file;
	
	file.open("example.txt", ios::binary | ios::in | ios::out | ios::app); // opens the text file that is being writen in
	
	cout << "Command Propt Text To Text File" << endl;
	cout << "Input what you would like to put into your text file" << endl;
	getline(cin, sentence);//gets the input of "sentence" with SPACES

	file.write(reinterpret_cast <char *> (&sentence), sizeof(sentence)); //input the text of "sentence" int the text file

	return 0;
}

when i input "hi"
i get "0L· hi ÌÌÌÌÌÌÌÌÌÌÌÌÌ  0La hi ÌÌÌÌÌÌÌÌÌÌÌÌÌ"
There are a couple of problems with your code. First you can't write a std::string to a file using the write function. When you try to write the std::string as you are trying you will actually be writing the address of the internal buffer, not the actual characters. And don't forget to "read" the data you need to know exactly how many bytes were written for this string, remember strings are dynamic.

Second a binary file is considered non-human readable, you're writing bytes, not characters. If you want to read the file you really need to use some kind of hex editor, or hexdump type of program.
So is there anyway to take what i have imputed into the cmd and put it into a text file?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::cout << "Command Propt Text To Text File\n"
              << "Input what you would like to put into your text file\n" ;

	std::string sentence;
	std::getline( std::cin, sentence ); //gets the input of "sentence" with SPACES

	std::ofstream( "example.txt" ) << sentence << '\n' ; // write the text of "sentence" into the text file
}

http://coliru.stacked-crooked.com/a/bbc23e8740069a53
Topic archived. No new replies allowed.