簡體   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