繁体   English   中英

如何将数字从一个文本文件复制到另一个文本文件但使它们成为下一个数字?

[英]How do I copy numbers from one text file to another but make them the next number?

我需要从一个文本文件中复制数字并将它们输入到另一个文本文件中,但将它们设为下一个数字,例如 1->2 3->4 ... 9->0 我已经把复制部分弄下来了,但不知道如何让一个数字成为下一个。

#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;
}

我输入 1 2 3 4 5 并期望输出为 2 3 4 5 6

您可以检查输入字符是否为数字,然后增加它,例如:

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

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

        content += currentChar;
    }

扩展 Oded Radi 的答案,

如果您希望 9 变为 0(如您所描述的),您需要处理它,这是一种方法:

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

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

    content += currentChar;
}

如果您的输入由空格分隔,则您的循环可以很简单:

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

另一个循环可能是:

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

上面的循环将数字限制为 0 到 9。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM