多次交换文件中的字符
Swapping chars in a file, multiple times
我有工作的代码,但只有一次。我需要一个输入字符a
和一个输入字符b
交换。在第一次循环中,它很好地交换了两个选定的字符,但是在第二次和之后的迭代中,它除了保持outFile不变外什么也不做。我如何交换两个以上的字符,直到我想停止?
ifstream inFile("decrypted.txt");
ofstream outFile("swapped.txt");
const char exist = 'n';
char n = ' ';
char a = 0;
char b = 0;
cout<<"nDo u want to swap letters? press <n> to keep letters or any button to continue:n"<<endl;
cin>>n;
while (n != exist)
{
cout<<"nWhat is the letter you want to swap?n"<<endl;
cin>>a;
cout<<"nWhat is the letter you want to swap it with?n"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c == b )
{
outFile<< a;
}
else if (c == a)
{
outFile<< b;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"nAnother letter? <n> to stop swappingn"<<endl;
cin>>n;
}
考虑不同的方法。
收集查找表中的所有字符交换。默认情况下,translate['a'] == 'a'
的输入字符与输出字符相同。要将a
与z
交换,只需设置translate['a'] = 'z'
和translate['z'] = 'a'
。
然后对文件执行一次遍历,同时复制和翻译。
#include <array>
#include <fstream>
#include <iostream>
#include <numeric>
int main()
{
std::array<char,256> translate;
std::iota(translate.begin(), translate.end(), 0); // identity function
for (;;)
{
char a, b;
std::cout << "nEnter ~ to end input and translate filen";
std::cout << "What is the letter you want to swap? ";
std::cin >> a;
if (a == '~') break;
std::cout << "What is the letter you want to swap it with? ";
std::cin >> b;
if (b == '~') break;
std::swap(translate[a], translate[b]); // update translation table
}
std::ifstream infile("decrypted.txt");
std::ofstream outfile("swapped.txt");
if (infile && outfile)
{
std::istreambuf_iterator<char> input(infile), eof;
std::ostreambuf_iterator<char> output(outfile);
// this does the actual file copying and translation
std::transform(input, eof, output, [&](char c){ return translate[c]; });
}
}
您已经读取了整个文件,因此不会读取更多字节或写入更多字节。您可以使用seek返回到开头,或者直接关闭并重新打开文件。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从文本文件中读取数值,直到遇到字符类型?
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 尝试将字符串从文件读取到无符号字符向量中
- 如何在C++中反转文本文件中字符的顺序?
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 如何存储 unicode 字符并将其输出到文件?
- 无法将整个文本文件复制到字符数组
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- 将未签名的字符写入输出文件
- 从我的 2DgridArray 中的文本文件中获取每个字符
- ifstream 读取的字符与文件中写入的字符不同
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 从文本文件 (C++) 生成字符矩阵
- 使用指针编译代码后,.cpp文件将变为随机字符
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 跨平台UTF-8字符文件数据编码/解码