Elijah
Elijah

Reputation: 15

Reading files into program

I am attempting to write a program that: -reads a text file, then puts it into a string -change each letter in the string by subtracting 4 -outputs the changed lines

I understand how to input/output files. I do not have much more code than that and am rather stuck as this is a very new concept for me. I have researched and cannot find a direct answer. How do I input each line of the original file into a string and then modify it?

Thank you!

// Lab 10
// programmed by Elijah

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main()
{
    fstream dataFile;
//Set the file "coded" as the line input
    dataFile.open("coded.txt", ios::in);

//Create the file "plain2" as program output
    dataFile.open("plain2.txt", ios::out);

}

Upvotes: 0

Views: 67

Answers (2)

j_v_wow_d
j_v_wow_d

Reputation: 511

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    ifstream inFile ("coded.txt"); //explicitly input using ifstream rather than fstream
    ofstream outFile ("plain2.txt"); //explicitly output using ofstream rather than fstream
    string str = "";
    char ch;
    while (inFile.get(ch))
    {
        if (ch!='\n' && ch!=' ')
        {
            //do your manipulation stuff //manipulate the string one character at a time as the characters are added     
        }str.push_back(ch); //treat the string as an array or vector and use push_back(ch) to append ch to str
    }
}

This more explicitly opens both an input and output file stream then creates an empty string and unitilized character. inFile.get(ch) will return true so long as it is not at the end of the file and will assign the next character to ch. Then inside the loop you can do whatever you need to do with ch. I just appended it to the string but it sounds like you will want to do something before appending.

In your case the get(ch) will be better than a getline() or >> method because the get(ch) will also add spaces and tabs and other special character that are part of the file which getline() and >> will ignore.

If by string-4 you mean the characters that are 4 less in the manipulation line you can use:

ch = ch-4;

Note that this could give results different than what you expect if ch initially was 'a', 'b', 'c', or 'd'. If you want wrap-around use ascii manipulation and the modulo operator (%).

Upvotes: 1

arc_lupus
arc_lupus

Reputation: 4114

You are overwriting your dataFile, therefore you either have to create a second fstream or process the strings first and afterwards use the same fstream for output.
String reading:
http://www.cplusplus.com/reference/string/string/getline/
String modifying:
http://www.cplusplus.com/reference/string/string/replace/ And what do you mean with "String - 4"?

Upvotes: 0

Related Questions