[英]How do I copy numbers from one text file to another but make them the next number?
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.我需要从一个文本文件中复制数字并将它们输入到另一个文本文件中,但将它们设为下一个数字,例如 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;
}
I enter 1 2 3 4 5 and expect the output to be 2 3 4 5 6我输入 1 2 3 4 5 并期望输出为 2 3 4 5 6
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;
}
Expanding on the answer from Oded Radi,扩展 Oded Radi 的答案,
If you want 9 to become 0 (as you described) you need to handle that, this is one way:如果您希望 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;
}
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.上面的循环将数字限制为 0 到 9。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.