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

Input values not saved correctly in char arrays

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

/*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 ([=19=]) 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 情况相同。