本文主要是介绍C //习题10.3 从键盘输入一个字符串,将其中的小写字母全部转换成大写字母,然后输出到一个磁盘文件“test“中保存,输入的字符串以“!“结束。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C程序设计 (第四版) 谭浩强 习题10.3
习题10.3 从键盘输入一个字符串,将其中的小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存,输入的字符串以"!"结束。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针,函数的模块化设计,动态分配内存
说明:这里准备先写入的文件名称为Test.txt,文件已经存在于该项目目录下。
#include <stdio.h>
#include <stdlib.h>void initialVar(char **name, char **word){*name = (char*)malloc(80 * sizeof(char));*word = (char*)malloc(sizeof(char));
}void inputFileName(FILE **file, char *name){printf("Enter File Name: ");scanf("%s", name);*file = fopen(name, "r");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}
}void fileInput(FILE **file, char *name, char *word){*file = fopen(name, "w+");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}printf("Enter String: ");while((*word = getchar()) != '!'){if(*word >= 'a' && *word <= 'z'){*word -= 32;}fputc(*word, *file);}fclose(*file);putchar(10);
}void freeVar(char **name, char **word){free(*name);free(*word);
}int main(){FILE *file = NULL;char *name = NULL;char *word = NULL;initialVar(&name, &word);inputFileName(&file, name);fileInput(&file, name, word);freeVar(&name, &word);system("pause");return 0;
}
运行结果如下:
这篇关于C //习题10.3 从键盘输入一个字符串,将其中的小写字母全部转换成大写字母,然后输出到一个磁盘文件“test“中保存,输入的字符串以“!“结束。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!