C语言检查abc字母表

标签 c arrays loops character

刚开始学C语言的循环。

Write a program that checks if the input of abc alphabet is correct, the input is small letters form abc alphabet, asume that the input is orderd, if misissing some latters you should add the missing latter with capital.in the end of the input there is a $ sign.

exampls:

for the input: abcdijklmnstuvyz$ should print abcdEFGHijklmnOPQRstuvWXyz

for the input: abefghijkopqrvwxyz$ should print abCDefghijkLMNopqrSTUvwxyz

我的想法是使用两个数组来表示 'a,b,c' 字母表,并在校正后使用另一个数组,这是我的代码:

#include <stdio.h>

int main()
{
    char student[26] = {0};
    char real[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 'c', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    char corection[26] = {0};
    int istudent = 0, ireal = 0, icorection = 0;

    for(istudent = 0; istudent<26; istudent++)//changed to < instad of <=
    scanf("%c", &student[istudent]);

    for(istudent = ireal = icorection = 0; (istudent < 26) && (ireal < 26); icorection++)
    {
        if (student[istudent] == real[ireal])
           {
           istudent++;
           ireal++;
           corection[icorection] = student[istudent];
           }
        if (student[istudent] != real[ireal])
           {
           istudent++;
           ireal++;
           corection[icorection] = (real[ireal] - 32);
           }

    }
   // print results
    int k;
    printf("printed array: \n");
    for(k=0;k<26;k++)
        printf("%c", corection[k]);
    return 0;
}

我正在尝试打印结果以检查我是否编写了正确的代码,但它没有显示正确的输出

最佳答案

for(istudent = 0; istudent<26; istudent++)//changed to < instad of <=
    scanf("%c", &student[istudent]);

这是您的代码/逻辑中的问题。您希望用户始终输入 26 个字符,并且只输入 26 个字符。

你需要的是,当你看到 $ 时停下来

所以你可以改变你的循环

for(istudent = 0; istudent<26; istudent++){
    scanf("%c", &student[istudent]);
    if(student[istudent] == '$')
        break;
}

或者您可以使用

读取字符串
scanf("%s", student);

其次,您总是在 for 循环中检查两个条件。如果第一个条件为真,您希望跳过第二个条件。

所以你可以使用 if - else if 。

将您的代码更改为 -

else if (student[istudent] != real[ireal])

最后在条件内,因为你首先递增,你需要在访问数组时使用 istudent -1

istudent++;
ireal++;
corection[icorection] = student[istudent-1];

另外你不应该在第二个条件下递增 istudent,否则你会跳过字符。

这是一个Demo修复了所有错误。

编辑:

正如 PeterPaulKiefer 所建议的,您可以进行多项改进 首先 - ire​​al 和 icorrection 总是一起变化并且总是具有相同的值。您可以消除其中之一。

其次,需要检查第二个条件,如果第一个为假,第二个必然为真。所以你可以只写else

最后,为了更好的可读性,您可以更改 istudent 和 ireal 的增量,以便在索引到数组后完成。

corection[icorection] = student[istudent];
istudent++;

关于C语言检查abc字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43954103/

相关文章:

objective-c - 当在同一个并发队列的 dispatch_sync 中调用 dispatch_apply 时内部会发生什么

c - i = i + j; 和有什么区别?我+=j;用c语言?

c - 通过嵌套结构访问指针

c - 如何获取已安装文件系统的列表

java - 计算 Java 中 String[] 中 String 出现次数的一行代码?

java - 循环遍历数组的各个部分

python - 如何检查for循环是否在python中完全结束?

C:内存中的循环、条件、结构

arrays - Excel VBA - 如何重新调整二维数组?

c - C语言中将变量放入数组中