C++ 如何将所有文件字符转换为大写或小写?
我尝试将文件中的每个字符都提取出来,并与touper和tolower函数一起使用。但是我不能用结果来代替角色 我用一个向量来解它 有没有简单的方法来解决这个问题C++ 如何将所有文件字符转换为大写或小写?,c++,C++,我尝试将文件中的每个字符都提取出来,并与touper和tolower函数一起使用。但是我不能用结果来代替角色 我用一个向量来解它 有没有简单的方法来解决这个问题 void UpperCase(){ fstream file; char name[81] , ch; vector<char> container; cout << "Enter the file name : "; cin >> name; file
void UpperCase(){
fstream file;
char name[81] , ch;
vector<char> container;
cout << "Enter the file name : ";
cin >> name;
file.open(name,ios::in);
while(!file.eof() && !file.fail()){
file.get(ch);
container.push_back(toupper(ch));
}
file.close();
file.open(name,ios::out);
for(int i=0 ; i<container.size()-1 ; ++i){
file.put(container[i]);
}
file.close();
return;
}
以下是一个有效的方法:
char buffer[4096];
std::string name;
std::cout << "Enter filename: ";
std::cin >> name;
std::ifstream input(name.c_str(), ios::binary);
const std::string out_filename = name + ".upper_case";
std::ofstream output(out_filename.c_str(), ios::binary);
while (input.read(buffer, sizeof(buffer))
{
const unsigned int chars_read = input.gcount();
std::transform(&buffer[0], &buffer[chars_read],
&buffer[0], toupper);
output.write(buffer, chars_read);
}
上面的代码读入一个字符块,然后将其转换为大写,然后将该块写入另一个文件
写入另一个文件是一种安全的做法,您不需要将整个文件读入内存
您可以更改缓冲区的大小以提高程序的效率。推荐大小是512的倍数,因为这是硬盘驱动器扇区的标准大小
编辑1:
如果您对std::transform过敏,请使用循环替换该调用以转换字符 我敢肯定在某个地方涉及到了代码。我们读心术很差。请注意,缓冲区不符合toupper,如:Yes,toupper需要一个int作为其参数,缓冲区为char。缓冲区应为无符号char。