Reading and writing files and examining characters

Write your question here.

I have two files, one with text that needs decoding "encoded.message" and one for an output file "output.txt". I want to import and the encoded message one character at a time, then I already have some code to change the text, but at the moment I just want to export the text character by character to "output.txt". However I don't understand the terminology required to import, export and examine and transfer characters. I am sure its really simple, but help would be appreciated.

On re-reading - I think I should point out that I am not really trying to decode encrypted messages - it is just part of the course that I am struggling with at the moment!
http://www.cplusplus.com/doc/tutorial/files/
http://www.mochima.com/tutorials/fileIO.html

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

int main ()
{
    const char* const input_file_name = __FILE__ ; // "whatever.txt"
    const char* const output_file_name = "out.txt" ;

    // open the files
    std::ifstream input_file(input_file_name) ;
    std::ofstream output_file(output_file_name) ;

    char c ;
    while( input_file.get(c) ) // for each character (including white space) in input
    {
        const char modified = std::toupper(c) ; // some code to change the text
        output_file.put(modified) ; // write the modified character to output
    }
}

http://coliru.stacked-crooked.com/a/42d7603c21cf21ba
closed account (NUj6URfi)
Use tokens with the separator being "".
Ignores whitespace, requires input file to be redirected to the program using input redirection
./myprog < encoded.message


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
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
	ofstream out ("output.txt", ifstream::out);
	if (!out.good())
	{
		cerr << "File: output.txt did not open properly!\n";
		return 1;
	}

	string contents;
	char bt;
	cin.seekg(0, ios::end);
	contents.resize(cin.tellg());
	cin.seekg(0, ios::beg);
	cin.read(&contents[0], contents.size());
	istringstream iss(contents);
	
	while(iss >> bt) // ignores whitespace
	{
		// do something with bt
		out << bt;
	}
	return 0;
}
Last edited on
Topic archived. No new replies allowed.