循环重复printf但不重复scanf

时间:2018-06-30 13:08:03

标签: c scanf

我制作了一个简单(难看)的程序来检查用户输入的大写,小写,数字和美元符号的密码。问题是我的dof循环开始时我的printf尴尬地重复了自己,而scanf甚至没有停止它,重复的过程取决于用户的输入。我用一些注释来解释代码,然后做一些截屏,向您展示我重复printf的意思。

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

int main(){
char pass[10];
int i,t,x,y,z;
t=y=z=0;

do{
    printf("Enter a password it needs to have an uppercase letter a lowercase one, a number and a $ sign: ");
    scanf(" %c", pass);



    //here i test for upper case, letter by letter
    for(i=0;i<10;i++){
        if(isalpha(pass[i])){
            if(isupper(pass[i])){
                t++;
            }
        }
    }

    //here i test for lower case, letter by letter
    for(i=0;i<10;i++){
        if(isalpha(pass[i])){
            if(islower(pass[i])){
                y++;
            }
        }
    }

    //here i test for number, letter by letter
    for(i=0;i<10;i++){
        if(isdigit(pass[i])){
            z++;
        }
    }

    //here i look for the dollar sign
    for(i=0;i<10;i++){
        if(pass[i]=='$'){
            x++;
        }
    }

    printf("\n");

    //if all the tests were true the variables t,x,y and z would not be 0
}while(t==0 || x==0 || y==0 || z==0);

}

代码的第一个显示工作正常: enter image description here

无论您在这张图片中看到什么,当我输入错误密码时,printf都会重复: enter image description here

和printf的重复取决于用户输入的数量: enter image description here

即使我输入了正确的密码,在代码结束之前,printf也会重复多次: enter image description here

我假设问题出在do while循环中的for循环中,但我只是找不到问题的确切出处以及为什么printf如此奇怪地重复

1 个答案:

答案 0 :(得分:0)

主要问题在于:

scanf(" %c", pass);

这将尝试扫描单个字符。要扫描字符串,请使用:

scanf("%9s", pass);

9限制了可以输入的字符数以避免溢出。不使用10是因为您需要为字符串结尾标记('\ 0')留出空间。

其他一些改进:

do{
    // Move here to reset each time
    t = y = z =0;

    printf("Enter a password it needs to have an uppercase letter a lowercase one, a number and a $ sign: ");

    // Should always test the result of scanf
    if (1 != scanf("%9s", pass)) {
        // Some error
        break;
    }

    // Combine all the for loops
    for (i = 0; pass[i]; i++) {
        if (isupper(pass[i])) {
            t++;
        }
        else if (islower(pass[i])) {
            y++;
        }
        else if (isdigit(pass[i])) {
            z++;
        }
        else if (pass[i] == '$'){
            x++;
        }
    }

    printf("\n");

    //if all the tests were true the variables t,x,y and z would not be 0
} while (t==0 || x==0 || y==0 || z==0);