c - 输入值未正确保存在 char 数组中

标签 c arrays string char fgets

代码有什么问题?值未正确保存在数组中。

/*Deklaration und Initialisierung*/
float addition1=15, addition2=9, subtrahend1=5, subtrahend2=2;
double multiplikation1=9, multiplikation2=21, divident1=10, divident2=2;

const char passwort[]="15sdDv4";
const char username[]="KevKevin";
char tippedpasswort[8], tippedusername[8];
fflush(stdin);

printf("******************* Identifikation ************************\n\n Benutzername: ");

fgets(tippedusername,9,stdin); 
printf(" Passwort: ");
fflush(stdin);
fgets(tippedpasswort,9,stdin);

printf("Tippeduser: %s\nTippedpassword: %s\nUser: %s\nPassword: %s\n",tippedusername, tippedpasswort, username, passwort);
system("pause");

if (strcmp(tippedusername,username) != 0 || strcmp(tippedpasswort,passwort) != 0) {
    printf("\nMELDUNG: Passwort oder Benutzername leider falsch!\n");
    return 0;
}

最佳答案

我猜这是德语,对吧?唉,我不明白。

第 1 点

引用 C11 标准,第 7.21.5.2 章,(强调我的)

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

fflush(stdin);undefined behaviour .

第 2 点

我认为您的 fgets() 有误。根据 man page

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer.

少一个是由于需要放置 null,因此,您应该提供准确的分配大小,而不是 +1

你必须改变

fgets(tippedusername,9,stdin);

fgets(tippedusername,8,stdin);

fgets(tippedusername,sizeof tippedusername,stdin);

对于 tippedpasswort 情况也是如此。

关于c - 输入值未正确保存在 char 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30093238/

相关文章:

c++ - 为什么整数到字符串的转换直到现在才明确包含在 C++ 中?

c - 如何确定 snprintf 目标缓冲区大小

javascript - 如何一次将一个元素多次添加到数组中

c# - 结构中字符串的管理

c# - 用于患者管理的列表/数组

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

string - 将具有相似名称的文件连接在一起

c - fopen - C 中作为流数据的原始数据

python - 如何连接 Python 和 C 程序?

c - 使用 atof() 将一组字符转换为 float