C语言中从键盘输入一行字符串,将其中的小写字母全部转换成大写字母,大写字母转为小写字母,其它字符不变,输出到磁盘文件 out.txt 中保存。输入的字符串以回车键结束。 (1)假设文件out.txt就在当前目录下,不需要加任何路径。 示例: 键盘输入:heLLO,How Are You? [out.txt]文件中内容为: HEllo,hOW aRE yOU?
时间: 2024-02-17 13:05:01 浏览: 25
好的,下面是C语言程序的答案:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp = fopen("out.txt", "w");
char c = getchar();
while (c != '\n') {
if (islower(c)) {
c = toupper(c);
} else if (isupper(c)) {
c = tolower(c);
}
fprintf(fp, "%c", c);
c = getchar();
}
fclose(fp);
return 0;
}
```
其中,我们使用getchar从键盘逐个读入字符c,根据题目要求,我们将小写字母全部转换成大写字母,大写字母转为小写字母,其它字符不变,然后将转换后的字符输出到out.txt文件中。最后记得关闭文件指针。
相关问题
实现将一用C语言编程输入一个字符串将其中小写字母全部转换为大写字母。
以下是一个简单的 C 语言程序,可以将输入的字符串中的小写字母转换为大写字母:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i;
printf("Enter a string: ");
gets(str);
i = 0;
while (str[i]) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
i++;
}
printf("String in uppercase: %s", str);
return 0;
}
```
该程序首先使用 `gets()` 函数从用户输入中读取一个字符串,并使用 `islower()` 函数检查每个字符是否为小写字母。如果是,就使用 `toupper()` 函数将其转换为大写字母。最后,程序输出转换后的字符串。需要注意的是,`gets()` 函数不安全,建议使用更安全的 `fgets()` 函数代替。
通过c语言写从键盘输入一个字符串,将其中的大写字母变成小写字母,其它字符不变。
可以使用C语言内置的字符处理函数toupper()和tolower()实现大写字母转小写字母的功能。
下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i;
printf("Enter a string: ");
fgets(str, 100, stdin); // 从键盘读入字符串
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) { // 判断是否为大写字母
str[i] = tolower(str[i]); // 转换成小写字母
}
}
printf("Lowercase string: %s", str);
return 0;
}
```
注意,使用fgets()函数可以避免输入字符串时出现缓冲区溢出的问题。