【发布时间】:2016-07-09 03:53:55
【问题描述】:
我正在尝试制作一个小型帐户注册程序。它提示用户输入userID 和password。我正在处理userID 部分,但它似乎不对。如果我输入< 8 字符userID,它工作正常,但是当我输入超过16 字符的userID 时,要求用户输入不同userID 的消息会打印两次。这是为什么呢?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
// Setting up variables
char userID[18];
char passcode[51];
// Firstly promt the user for user ID
do // This loop is for asking the user to type another userID if his chosen one isn't approprite
{
printf("Please choose your user ID! (it must be between 6 - 16 charaters long)\n");
for (int i = 0; i < 17; i++) // This loop store the userID into the character array
{
userID[i] = getchar(); // Store userID into array character by character
if (userID[i] == '\n')
{
userID[i+1] = '\0';
break;
}
}
}
while (strlen(userID) < 7 || (strlen(userID) > 16 && userID[16] != '\n'));
// Printing info on the screen.
printf("Your acount info are:\n\tuserID : %s\tpasscode: ", userID);
【问题讨论】:
-
请发布代码以了解您的问题中的错误。谢谢。
-
T.T我是新手,所以我还不能发布图片T.T.你能看看链接吗:(。真的很感激
-
您不必发布图片。您可以在问题本身中发布代码。
-
除非最后一个字符是换行符,否则您不会终止输入字符串,如果字符串太长,最后一个字符不是换行符。这会导致未定义的行为。
-
我的评论不是答案——它只是对问题的诊断(好吧,一个问题),而不是修复。您可能还没有足够的代表对 cmets 进行投票,但在适当的时候您将能够这样做。别担心;如果我写了一个答案,那么情况会有所不同,但是 cmets 名义上是短暂的(即使它们可以持续数年)。