【问题标题】:Why wont my input from scanf print correctly?为什么我的 scanf 输入不能正确打印?
【发布时间】:2013-09-28 03:05:52
【问题描述】:

我的程序从输入中扫描并打印所有使用的大写字母。

我也在尝试在程序结束时从标准输入打印原始输入。

但是当我使用 printf 时,它似乎跳过了输入表达式的第一部分,将剩余的内容打印在我的字符数组中。请帮我看看问题出在哪里。 -代码中的cmets-

#include <stdio.h>

int main(void){

char input[81];
int letters[91];
int i;

    //initialize arrays input and letters
for (i = 0; i < 90; i++) letters[i] = 2;
for (i = 0 ; i < 80; i++) input[i] = 'a';
i = 0;  

    //reads into input array until EOF
while((scanf("%c",input)!= EOF)){

    //checks input for characters A-Z 
    if((input[i]>= 'A' && input[i]<= 'Z'))


       letters[input[i]] = 1;
    }

    //prints capital letters from input that occur at least once
for(i = 'A'; i < 'Z'; i++){
    if (letters[i]==1)
    printf("%c", i);}        // this output works fine, the scan worked??


//print blank line
printf("\n\n");


// print input
printf("%s\n", input);      //This is where the incorrect output comes from.  

return 0;}

我原来的输入有变化吗?为什么? 我的输入一开始没有被正确扫描吗? 请尽快回复!

【问题讨论】:

    标签: c printf scanf


    【解决方案1】:

    这里:

    while((scanf("%c",input)!= EOF)){
    

    您只会将字符读入input[0]。这对于您为 letters 所做的工作来说很好,但很明显,当您尝试打印出 input 时,它不会像您预期的那样工作。

    当您修复它时,您还需要记住在最后一个输入字符之后添加终止 \0

    【讨论】:

      【解决方案2】:

      scanf 循环一次读取您输入的一个字符,并将该字符存储在input[0] 中。当scanf 循环完全结束时,input[0] 包含读取的最后一个字符,input 的其余部分保持不变。

      要修复,您需要在scanf 循环的末尾包含i++

      顺便说一句,通过一次调用fgets 填充输入缓冲区然后循环输入缓冲区会更清晰(也更有效):for (i=0; buf[i]!='\0'; i++) { ... }

      【讨论】:

        【解决方案3】:

        你必须这样做

        while((scanf("%c",&input[i])!= EOF))
        {i++;}
        

        而不是这个

        while((scanf("%c",&input)!= EOF))
        {}
        

        您所做的是每次将字符扫描到数组中第一个元素的地址中,因此它会一次又一次地被覆盖。 input[] 数组的剩余部分未被访问,因此不会改变

        【讨论】:

        • 它必须是&amp;input[i]scanf() 需要一个地址。
        猜你喜欢
        • 2021-12-29
        • 2021-04-13
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-19
        • 1970-01-01
        相关资源
        最近更新 更多