c - 交换文件内的字符
问题描述
FILE* f; /// pointer to a File structure
char cuv[100];
int i;
f = fopen("exmp.txt", "a+"); /// open the file and add the registry. the end
puts("enter words to add to file");
for (i = 1; i <= 3; i++) {
gets(cuv); /// enters the character string
fprintf(f, "% s", cuv);
} /// write
puts("File contents:");
rewind(f); /// goes to the beginning of the file
fscanf(f, "% s", &cuv); /// read
puts(cuv); /// displaying the string on the screen by adding \ n
getch();
fclose(f);
} /// close the file
我有这个程序可以在文件末尾添加单词,它可以正常工作,但我希望它可以将字母 a 与字母 b 交换,反之亦然
我发现了一段代码可以满足我的要求,但我似乎无法让它工作。如果我更改某些内容,它只会破坏代码
for (int a = 0; a < strlen(cuv); a++){
if (cuv[a] == 'a'){
cuv[a] = m;
} else if(cuv[a] == 'b'){
cuv[a] = c;
}
}
有没有更简单的方法来交换 2 个字符?
解决方案
把这两个变成函数。
对于第二个,在你的函数中试试这个。我假设 nom 是您想要交换“a”和“b”的词。
# nome must be defined prior to this
for (int a = 0; a < strlen(nome); a++){
if (nome[a] == 'a'){
nome[a] = 'b';
} else if(nome[a] == 'b'){
nome[a] = 'a';
}
}
# nome must be returned at this point
就个人而言,我会为此目的选择除“a”之外的任何其他索引变量名称。
推荐阅读
- python-3.x - 如何使用 AbstractUser 类访问 request.user
- python - Discord 命令在同一参数中采用整数或字符串
- flutter - BottomNavigationBar 页面 Flutter 上缺少 AppBar
- selenium-webdriver - 从需要身份验证的网站上抓取数据 [硒不起作用],我可以拦截来自 .NET 的 chrome 请求吗?
- spring - 从 Spring 依赖管理获取 Hibernate 版本以在 Gradle 中配置插件
- azure-devops - Azure DevOps REST API 错误:您无权创建订阅
- python - 我已经使用 pip 在虚拟环境中安装了“black”,但是当我运行 python -m black my_module.py 时,它显示 No module named black
- python - 如何使用 WHERE 在 python 中更新 sqlite3 记录?
- python - 如果列值在另一个数据框中不存在,则从数据框中删除行
- c++ - 如何在 Linux (CentOS) 中使用完整路径运行 Fortran 编译器和 C 编译器