从文件中读取并交换c++中的特定字符
Read from a file and swap certain char in C++
在这个函数中,我需要将输入的文件中的所有字符(例如a
)替换为输入的另一个字符(例如i
)。我已经试过两次了,但作为新人,我的大脑已经太迟了,没有什么建议了吗?
void swapping_letter()
{
ifstream inFile("decrypted.txt");
char a;
char b;
string line;
if (inFile.is_open())
{
while (!inFile.eof())
{
getline(inFile,line);
}
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
replace(line.begin(),line.end(),a,b);
inFile<<line
inFile.close();
}
else
{
cout<<"Please run the decrypt."<<endl;
}
}
或:
void swapping_letter()
{
ifstream inFile("decrypted.txt");
char a;
char b;
if (inFile.is_open())
{
const char EOL = 'n';
const char SPACE = ' ';
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
vector<char> fileChars;
while (inFile.good())
{
char c;
inFile.get(c);
if (c != EOL && c != SPACE)
{
fileChars.push_back(c);
}
replace(fileChars.begin(),fileChars.end(),a,b);
for(int i = 0; i < fileChars.size(); i++)
{
inFile<<fileChars[i];
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
}
仔细看下面的代码:
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
它读取两个字符,不多也不少。如果你按下"ab enter",你就没事了,回车将是未读的,但这不会造成任何伤害——它会将"a"answers"b"读入两个变量中。但是如果你按"a enter b enter",它会读取"a"answers"enter"到两个变量中!
这样做的一种方法是读取原始文件,替换字符并将输出写入新文件。
最后,当你完成后,可能会用新的文件覆盖旧文件。
我将从一个相对简单的解决方案开始:
- 将文件的内容存储在
vector<char>
中(注意大文件) - 遍历vector的内容并执行swap
- 用矢量 的内容覆盖旧文件
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存