-3

I need to copy numbers from one text file and input them in another but make them the next number for example 1->2 3->4 ... 9->0 I have gotten the copying part down but cant figure out how to make one number the next.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ()
{
     ifstream infile("input.txt");
     ofstream outfile("output.txt");
     string content = "";`
     int i;`

     for(i=0 ; infile.eof()!=true ; i++) // takes content 
         content += infile.get();

     i--;
     content.erase(content.end()-1);     // erase last character

     cout << i << " characters read...\n";
     infile.close();

     outfile << content;                 // output
     outfile.close();
     return 0;
}

I enter 1 2 3 4 5 and expect the output to be 2 3 4 5 6

πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
  • See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Thomas Matthews Feb 17 '19 at 19:38

3 Answers3

1

You can check if an input char is a digit, then increase it, something like:

    for (i = 0; infile.eof() != true; i++)// takes content 
    {
        char currentChar = infile.get();

        if (isdigit(currentChar))
        {
            currentChar++;
        }

        content += currentChar;
    }
OdedR
  • 123
  • 7
  • See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong. – Thomas Matthews Feb 17 '19 at 19:37
1

Expanding on the answer from Oded Radi,

If you want 9 to become 0 (as you described) you need to handle that, this is one way:

for (i = 0; infile.eof() != true; i++) // takes content 
{
    char currentChar = infile.get();

    if (isdigit(currentChar))
    {
        currentChar = (((currentChar - '0') + 1) % 10) + '0';
    }

    content += currentChar;
}
  • See [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Thomas Matthews Feb 17 '19 at 19:38
1

If your input is separated by whitespace, your loop can be simple:

int value;
while (input_file >> value)
{
  value = value + 1;
  output_file << value << " ";
}

Another loop could be:

int value;
while (input_file >> value)
{
    value = (value + 1) % 10;
    output << value << " ";
}

The above loop restricts the numbers from 0 to 9.

Thomas Matthews
  • 52,985
  • 12
  • 85
  • 144