Skip to content Skip to sidebar Skip to footer

How to Make Program Read Inuts From File

Writing a programme to read an input file

Y'all accept to write a programme to read an input file graphic symbol by character to assistance Peter solve the post-obit activity in his activity book. The paragraph below is given:
Nosotros h2pe that 32u e5723ed the acti4it3. A6ter 32u ha4e c2mpleted the acti4it3, 0e5d 32ur re0ult t2: The Acti4it3 C2mpetiti25, Bett3 Da4i0 0treet 99, Auckla5d Park, 989, a5d 0ta5d a cha5ce t2 wi5 a hamper c250i0ti51 26 c2l2uri51 a5d acti4it3 b22k0, c2l2uri51 pe5cil0 a5d pe50.
Create an input file activity.dat with the paragraph above. The numbers 0 to 7 have to exist replaced as follows:
0 must be replaced by south
1 must be replaced by one thousand
2 must be replaced by o
iii must exist replaced by y
four must be replaced by five
5 must exist replaced by due north
6 must be replaced by f
seven must be replaced past j
Inquire the user to input the names of the input and output files. Read the input file character by grapheme, and write the character (if it stays the same) to the output file, or write the inverse character to the output file. Call your output file competition.txt

So,if im intepreting this right , I have to brand a txt.file and re-create paste the paragraph , then write a plan to read that txt.file and then output it to some other txt.file with the replacements?

If then, can someone just assist with how you actually can do that? DON"T WRITE THE WHOLE CODE. but explain to me how y'all actually are able to let it read it and convert it?

Currently using code_blocks and doing it all via console

> so write a plan to read that txt.file then output it to some other txt.file with the replacements?
Yes.

As a useful offset exercise, merely see if yous can brand an authentic re-create of the input file without any substitutions.

                          one
2
3
four
5
6
vii
eight
nine
ten
11
                                                      char                            transform_char(char                            c) {                            return                            c; }                            int                            main ( ) {                            char                            c;                            // fin and fout are opened fstreams                            while                            ( fin.get(c) ) {     c = transform_char(c);     fout.put(c);   } }                        

The next step is brand transform_char deal with just one of the substitutions.
You re-test and make certain your output file is heading in the right direction.

And so,if im intepreting this right , I have to make a txt.file and copy paste the paragraph , then write a plan to read that txt.file and then output it to another txt.file with the replacements?

This is more or less right and shows your plan/framework (pseudocode even), maybe change a few things and aggrandize on it equally follows:

                  ane. Make a .txt file ( call information technology some_text.txt ) 2. Manually re-create paste the paragraph into the file 3. Create a new file for output (output.txt) iv. Write a program to read that .txt file character by character 5a. --- Process each character by making replacements 5b.     Save processed character to output.txt file 5c.  --- Loop until there are no more characters 6. All done and then close files.                

make the text file in notepad to first: the consignment says to read the file, but not where it came from, so it is user provided non code generated.

at present write code to open the file, read it in letter of the alphabet by letter (their pick, they told you lot do do it this manner) and perform the lookup and exchange.

by the style, bank check this out:
unsigned char tbl[256];
std::iota(tbl, tbl+ 256, 0); //this is just filling the tabular array with 0-255 which you can exercise in a loop if you lot want.
tbl['0'] = 'south'; //0 and '0' are not the same. it must exist in quotes here
tbl['i'] = 'g';
... fill in the remainder of these...
the output you want is (ofs is ofstream ifs is ifstream variable proper noun examples)
ofs << tbl[inputletter];

so basically with the to a higher place table all you need is:
ifs >> letter;
ofs << tbl[letter of the alphabet]; //when letter == '0' y'all become south, because of the table conversion.

there are examples in the reference section on this site on how to practise the two files. they work a lot like cin and cout:
ifstream ifs(infilename); //opens infilename, simply you demand to check to see if it worked (that is, handle a bad file proper noun from user)
ifs >> letter; //works similar cin
ofstream ofs(outfilename); //you create or over-write this one, no demand to check however it can fail if user said to make information technology in a read only place or nonexistent drive letter etc..! You can probably skip that for your homework, but know that you do need to check it in a serious program
ofs << letter; //works like cout

you tin can also check each letter with if statements or a switch statement to manually convert information technology.
if(letter == '0') .. do something
else if(letter == '1')
else if ... //over and over
else default activity ...

Concluding edited on

You can also employ 2 strings - before and later. If find read char in earlier string and then supplant with later char std::string.discover()

                          1
2
                                                      const                            std::string earlier {"01234567"};                            const                            std::cord after {"sgoyvnfj"};                        

ifs >> letter;

ignores white space unless you also use std::noskipws

Final edited on

                          1
two
3
four
five
6
7
8
nine
ten
11
12
13
14
15
sixteen
17
xviii
19
20
21
22
23
24
25
26
27
28
                                                      #include <iostream>                            #include <fstream>                            #include <vector>                            using                            namespace                            std;                            int                            main() {     cord filename("activity.txt");     vector<char> bytes;                            char                            byte = 0;      ifstream input_file("action.txt");                            if                            (!input_file.is_open()) {         cerr <<                            "Could not open the file - '"                            <<                            "activity.txt"                            <<                            "'"                            << endl;                            render                            EXIT_FAILURE;     }                            while                            (input_file.get(byte)) {         bytes.push_back(byte);     }                            for                            (const                            automobile                            &i : bytes) {         cout << i <<                            "-";     }     cout << endl;     input_file.close();                            return                            EXIT_SUCCESS; }                        

Here is my reading code so far, it worked , it displayed the words on the console.

I am now trying to figure out how to let that string work you gave me @seeplus

Last edited on

@OP
Information technology's possible to apply <vector>'s and <string>'s only given you starting post it'southward not necessary. You're simply reading a character, which is all y'all will do with <string> functionality and the <vector> would just exist useful if you wanted to shop the data in retention for some (unknown?) reason.
The challenge is to come up up with a way of efficiently performing the replacements and, aside from other possibilities, a couple of possibilities have already been mentioned - switches and if'south - at that place are other means too with mapping the characters.

                          1
2
3
4
5
6
7
8
nine
10
11
12
xiii
14
fifteen
16
17
xviii
nineteen
twenty
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
                                                      #include <iostream>                            #include <fstream>                            using                            namespace                            std;                            int                            main() {     string filename("activity.txt");                            char                            grapheme{};                            // SETUP READ FILE                            ifstream input_file("activity.txt");                            if                            (!input_file.is_open())     {         cerr <<                            "Could not open up the file - '"                            <<                            "activity.txt"                            <<                            "'"                            << endl;                            render                            EXIT_FAILURE;     }                            // SETUP WRITE FILE                            ofstream output_file("activity_output.txt");                            if                            (!output_file.is_open())     {         cerr <<                            "Could not open up the file - '"                            <<                            "activity_output.txt"                            <<                            "'"                            << endl;                            return                            EXIT_FAILURE;     }                            while                            (input_file >> grapheme)                            // NEVER Always FORGET TO USE noskipws                            {                            // Brandish WHAT IS BEING READ IN                            cout << character <<                            '\north';                            // PROCESS THE Character REPLACEMENTS (THIS IS JUST A DEMO/Test                            if(grapheme ==                            'e')             grapheme =                            '*';                            // WRITE RESULTS TO OUTPUT FILE                            output_file << character;      }                            // TIDY Upward                            input_file.close();     output_file.shut();                            return                            EXIT_SUCCESS; }                        

Terminal edited on

to figure out how to let that string work yous gave me @seeplus

Maybe:

                          1
ii
3
4
v
six
7
8
9
10
eleven
12
thirteen
14
fifteen
xvi
17
xviii
19
                                                      #include <iostream>                            #include <fstream>                            #include <string>                            int                            principal() {                            const                            std::string before {"01234567"};                            const                            std::string after {"sgoyvnfj"};  	std::ifstream input_file("activeness.txt"); 	std::ofstream output_file("competition.txt");                            if                            (!input_file || !output_file)                            return                            (std::cerr <<                            "Could not open files\n"), 1;                            for                            (char                            ch {}; input_file.become(ch); output_file.put(ch))                            if                            (const                            auto                            fnd {before.find(ch)}; fnd != std::cord::npos && fnd < afterward.size()) 			ch = after[fnd]; }                        

Terminal edited on

                          one
ii
                                                      const                            std::string before {"01234567"};                            const                            std::string after {"sgoyvnfj"};                        

@OP
I misread the significance of <string>'s in the earlier post thinking information technology meant reading the file into a string. I of the few occasions in my life where I accept to take dorsum a comment for being wrong. All the same that's some other manner of replacing the chars., and is one example of a mapping instead of a pile of if's or a switch which don't lend themselves to re-usability.
As you lot tin encounter none of these require <vector>'south

As per my previous comment, this ignores white space chars unless you also use std::noskipws

that is why I wasted the space for a total ascii table. If you go my route, it is but

                          ane
2
3
4
5
6
vii
8
9
x
eleven
12
13
14
                                                      while                            (input_file >> character)     {                            // Brandish WHAT IS Existence READ IN                            cout << character <<                            '\due north';                output_file << tbl[grapheme];                            /*          what happens is that every letter except the replaced ones is mapped to itself, and so e is  replaced with e,  x is replaced with 10, and then on... only the special ones are replaced as specified.  Its faster (no find, no conditions) and easier to write at the price of memory AND my technique is  non actually valid for unicode problems, unicode is as well big to map this way.        */                            }                        

Final edited on

I concur this is faster :)

                          one
2
3
four
5
half dozen
7
8
ix
10
11
12
13
xiv
15
xvi
17
18
nineteen
xx
21
22
23
24
                                                      #include <iostream>                            #include <fstream>                            #include <string>                            #include <numeric>                            int                            main() {                            const                            std::string before {"01234567"};                            const                            std::string after {"sgoyvnfj"};                            unsigned                            char                            tbl[256] {};  	std::iota(tbl, tbl + 256,                            static_cast<unsigned                            char>(0));                            for                            (size_t i = 0; i < before.size() && i < after.size(); ++i) 		tbl[before[i]] = after[i];  	std::ifstream input_file("activeness.txt"); 	std::ofstream output_file("contest.txt");                            if                            (!input_file || !output_file)                            render                            (std::cerr <<                            "Could non open files\n"), i;                            for                            (char                            ch {}; input_file.get(ch); output_file.put(tbl[ch])); }                        

I don't similar many assignments! :)

@OP
Lot'south of options and lots of choices to make now.

0p2ilt 62r ch2ice

Another way to translate the characters is a switch statement. This might exist clearer to a beginner, merely jonin's lookup table is probably faster.

                          one
2
3
four
5
6
seven
viii
                                                      while                            (infile.get(ch)) {                            switch(ch) {                            case                            '0': ch =                            's';                            intermission;                            case                            '1': ch =                            'chiliad';                            break;                            // etc.                            }     outfile.put(ch); }                        

No surprises with a <map> option:

                          ane
two
3
4
5
6
7
8
ix
10
11
12
13
14
15
sixteen
17
eighteen
19
xx
21
22
23
24
25
26
27
28
29
30
31
                          ...                            #include <map>                            using                            namespace                            std;                            int                            main() {      map<char,char> character_map;     map<char,char>::iterator iter;      character_map['0'] =                            's';     character_map['ane'] =                            'g';     character_map['2'] =                            'o';     character_map['three'] =                            'y';     character_map['4'] =                            'v';     character_map['5'] =                            'n';     character_map['6'] =                            'f';     character_map['7'] =                            'j';     ...                            // PROCESS THE Graphic symbol REPLACEMENT                            iter = character_map.detect(grapheme);                            if( iter != character_map.end() )             character = iter -> second; ...                            return                            EXIT_SUCCESS; }                        

ty all very much , I actually learned quite a lot today

my understanding is that most of the time, unless prevented past something, switches ARE lookup tables when compile. Its probably nigh the same, and in turn, the map is too pretty close to what I did.

Concluding edited on

Topic archived. No new replies allowed.

millerlostow.blogspot.com

Source: https://www.cplusplus.com/forum/beginner/278128/

Post a Comment for "How to Make Program Read Inuts From File"