【问题标题】:Using file and loop in c在c中使用文件和循环
【发布时间】:2020-05-22 23:08:56
【问题描述】:

在这个程序中,如何同时将大写字母转小写字母和小写字母转大写字母?

我试过很多次了,还是不行。

我的期望,例如

输入:

 from read.txt(orginal contant of the file:
 Hello World) 

输出

hELLO wORLD

这是我的代码.... (我只能从大写转换为小写。同时我不能从大写转换为小写和从小写转换为大写。

#include<stdio.h> 
#include<stdlib.h>
int main() 
{ 

    FILE* file;
    char ch;  

    file = fopen("read.txt","r"); 

    while (ch != EOF) 
    { 
        ch = toupper(ch); 

        printf("%c", ch); 

        ch = fgetc(file); 
    }  
    fclose(file);
    return 0; 

} 

【问题讨论】:

  • 您应该在 对其进行测试之前在某处阅读该字符。
  • “不工作”不是一个足够详细的诊断。它在做什么
  • 你甚至没有编译它。 6行程序记住变量名是不是太复杂了?

标签: c loops file


【解决方案1】:

这里有很多错误。

您首先检查未初始化的ch 变量,使用它并尝试打印,然后阅读它。顺序必须正好相反。

ch 必须是 int 类型才能容纳 EOF

你需要检查fopen是否成功

int main() 
{ 
    FILE* fptr;
    int ch;  

    fptr = fopen("read.txt","r"); 

    if(fptr)
    {
        while ((ch = fgetc(fptr)) != EOF) 
        { 
            ch = toupper(ch); 
            printf("%c", ch); 
        }  
        fclose(fptr);
    }
    return 0; 
} 

【讨论】:

  • fptr 是什么?此处未定义。含义file?
  • 哦,我明白了,这只是另一个需要修补的错误。不是你的坏!
【解决方案2】:
// Note that UPPER and lower chars differ by bit 5 (value 0x20).
// If you want to switch case for any [A-Za-z] in one step,
// an exclusive-OR (^ bitwise operator) can be used:

#include <stdio.h> 
#include <stdlib.h>
#include <ctype.h>

#define TOGGLE_CASE(c)  ((c) ^ 0x20)

int
main(void)
{ 
    FILE *file;
    char ch;  

    if ((file = fopen("read.txt", "r")) == NULL) {
        dprintf(2, "fopen error\n");
        return (1);
    }

    while ((ch = fgetc(file)) != EOF)
        printf("%c", isalpha(ch) ? TOGGLE_CASE(ch) : ch);
    fclose(file);

    return (0); 
}

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多