Ok, I want to read integers from a text file...a large sum of integers. The input is a regular text file, where each line is terminated with an end-of-line character. The file is gonna contain any valid ASCII symbol between 32 and 127. A number of strings ( no negative sign ). Like...

1+2+3+4+5
0 + 100
+492
+ 1000

Just some examples of input files. I want the output to be appended to a text file. If the output file does not exist, it should create it and append it after each run. Well, I find this to be tricky.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
     ifstream myReadFile("text.txt");
     string output;
     while (getline(myReadFile, output)) {
         cout << output << '\n';
     }
}

So this would read the file. I know I gotta still change things so the input can be handled correctly. I want the frame first. So read it from the text file and then create one and put it in there. How exactly can I do this? Could I use ofstream ?

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

Like this one? So first I would have ifstream and the ofstream comes right after it? This should creat the file. Maybe put the input into it, too. Sorry... kind of a a newbie here. I would appreciate if someone could help me with this!

Recommended Answers

All 8 Replies

You can append to a text file using the std::ios::app flag when you open it. So, if you want to read in from one file and append the contents to another file, you can do something like:

/* Open the input file & check that it opened OK */
std::ifstream inFile("file1.txt", std::ios::in);
if ( ! inFile.is_open() ){
   std::cerr << "Error: unable to open file for input" << std::endl;
   return 1;
}

/* Open the output file & check that it opened OK */
std::ofstream outFile( "file2.txt", std::ios::app );   // Open with append flag
if ( ! outFile.is_open() ){
   std::cerr << "Error, unable to open file for output" << std::endl;
   return 2;
}

/* Read from the input and append to the output file */
while ( inFile.good() ){
   std::string line;
   getline( inFile, line );   // Read the line from the input file

   /* Process the line here to get the bits that you want */

   outFile << line << std::endl;   // Write the file to the output file
}

You didn't mention what kind of processing that you wanted to do on the contents of the file before appending it to the output, so I left that bit for you to fill in :o)

Ok, I guess I was a little off. Thank you.
Well, it just need to add that empty lines can be skipped, invalid input numbers ( strings that are not numbers). So just manipulating the strings.

Question: Do I have to store the input? Like when I have manual input, I store it in an variable and then, when I want to work with it, I refer to the variable. Can I just manipulate the strings after line 18, or do have to store the input somewhere? I'm not sure if it automatically handles the input.

Ok, I guess I was a little off. Thank you.
Well, it just need to add that empty lines can be skipped, invalid input numbers ( strings that are not numbers). So just manipulating the strings.

Question: Do I have to store the input? Like when I have manual input, I store it in an variable and then, when I want to work with it, I refer to the variable. Can I just manipulate the strings after line 18, or do have to store the input somewhere? I'm not sure if it automatically handles the input.

First of all, I'm really sorry, but I'm answering on my phone and I think I might have accidentally flagged this as a bad post. It's not, obviously!

Once you use getline to get a line from the file into the line varible, then you can just go ahead and use it to do your manipulations, check there's something on the line and check for valid characters etc. It does kind of automatically handle the input, in the sense that everything is converted into a string and you have to take it from there.

First of all, I'm really sorry, but I'm answering on my phone and I think I might have accidentally flagged this as a bad post. It's not, obviously!

Once you use getline to get a line from the file into the line varible, then you can just go ahead and use it to do your manipulations, check there's something on the line and check for valid characters etc. It does kind of automatically handle the input, in the sense that everything is converted into a string and you have to take it from there.

Thank you! So, I just work with the "variable" line in this case? Treat it like a variable ? That would be easy then, though. Easier than I thought. I just put the loops etc right there. Sorry for the stupid question, but it's the first time that I am using this one. I am getting there, though. :)

Continuing on, yes, no need to call line a "variable" in quotes. It IS a variable, so of course you can treat it like one. So are inFile and outFile.

inFile is called an "instance" of class ifstream. outFile is an instance of class ofstream. line is an instance of class string. See this for a list of supported operations on string instances. There are also good tutorials on that site.

Great. Thank you all!

Ok, another question... would this not read the integers from the file and add them? O foucrse this is probably not going to work with + in between the integers. I am stuck with the processing part.

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

int main() {
    int sum = 0;
    int x;
    ifstream inFile;
    
    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }
    
    while (inFile >> x) {
        sum = sum + x;
    }
    
    inFile.close();
    cout << "Sum = " << sum << endl; 
    return 0;
}

Someone else told me I would have to parse it as well...although I thought the code given by ravenous will already get the information from the text file. I don't know..

Your code looks ok at first glance, as far as adding integers. Have you tested it yourself? If it doesn't work, what is it doing wrong?

Ravenous' code will certainly get the information from the text file, but at his line 20, his comment tells you that you now have to parse the information out of the line that you read from the file and do something with it.

Now that you have a line (instance of string), you can create a stream from it:

stringstream inTxt (line);

.
Then you can use inTxt pretty much exactly the way you use inFile, to read items out of line. You just need to check when inTxt is empty (use one of .good(), .bad(), .eof()) so you know when to get another line from inFile. If you are sure that integers and operators will always be separated by whitespace, you could read a string out of inTxt each time, and provide and call your own functions isInteger() and isOperator(). You could declare isInteger as:

bool isInteger(const std::string & str, int & val);

and have it return true if str represents an integer (and store the integer value into val), or false if str does not represent an integer (and leave val alone).

If the input can skip spaces between integers and operators, e.g. 3+5 instead of 3 + 5 , then you may need to iterate over line one character at a time, deciding what to do for each character.

As you're probably realizing, writing a robust parser is not a trivial task. Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.