简单的循环和字符串长度用C

简单的循环和字符串长度用C

本文介绍了简单的循环和字符串长度用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Visual Studio 2015 pretty新C.写作,我试图通过与fgets安全提示字符串的用户。我想利用与fgets来获取字符串,检查字符串太长,而且重新提示用户,如果它是直到他们进入一个良好的字符串。这里是我的code

I'm pretty new to C. Writing in Visual Studio 2015, I'm trying to safely prompt a user for a string by using fgets. I want to use fgets to get the string, check if the string is too long, and reprompt the user if it is until they enter a good string. Here is my code

/*
* Nick Gilbert
* COS317 Lab 2 Task 2
*/
#include "stdafx.h"
int main()
{
    char str[10];
    int isValid = 0;
    while (isValid == 0) {
        printf("Please enter a password: ");
        fgets(str, 10, stdin);
        if (strlen(str) == 9 && str[8] != '\n') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c
            printf("Error! String is too long\n\n");
            memset(&str[0], 0, sizeof(str));
        }
        else {
            printf(str);
            isValid = 1;
        }
    }
    printf("Press 'Enter' to continue...");
    getchar();
}

然而,当我运行这个并输入一个错误的字符串时,多余的字符得到反馈到下与fgets自动!

However, when I run this and enter a bad string, the excess characters get fed into the next fgets automatically!

我怎样才能解决这个问题做我想做的事情?

How can I fix this to do what I want it to do?

推荐答案

如果该字符串由与fgets 读不以换行符结束,通话与fgets 在一个循环,直到它,然后再提示用户。

If the string read in by fgets doesn't end with a newline, call fgets in a loop until it does, then prompt the user again.

    if (strlen(str) > 0 && str[strlen(str)-1] != '\n') {
        printf("Error! String is too long\n\n");
        do {
            fgets(str, 10, stdin);
        } while (strlen(str) > 0 && str[strlen(str)-1] != '\n') {
    }

另外,从来没有在第一个参数的printf 传递变量,尤其是当该变量的内容来自于用户输入的数据。这样做可能导致format字符串漏洞。

Also, never pass a variable at the first argument to printf, particularly if the contents of that variable comes from user entered data. Doing so can lead to a format string vulnerability.

这篇关于简单的循环和字符串长度用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:06