首页 > 解决方案 > 循环重复 printf 但不是 scanf

问题描述

我做了一个简单(而且丑陋)的程序来检查用户输入的大写、小写、数字和美元符号的密码。问题是我在 do while 循环开始时的 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);

}

代码的第一次显示工作正常: 在此处输入图像描述

但是,正如您在这张图片中看到的那样,当我输入错误的密码时,printf 会重复: 在此处输入图像描述

并且 printf 的重复取决于用户输入了多少: 在此处输入图像描述

即使我输入了一个好的密码,printf 在代码结束之前也会重复很多次: 在此处输入图像描述

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

标签: cscanf

解决方案


主要问题在于:

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);

推荐阅读