Im trying to compare user input string with the example inside function, using gets() and strcmp to do this.
I’ve tried this code:
#include <stdio.h>
#include <string.h>
int main() {
// example string
char userName[30] = "Alice Jane";
// string for storing user input
char userInput[30];
printf("Enter your text:n");
fgets(userInput, 30, stdin);
printf("Your text is: %sn", userInput);
printf("Real text is: %sn", userName);
int strComparing = strcmp(userName, userInput);
if (strComparing == 0) {
printf("Strings are equaln");
} else {
printf("Strings are not equal, difference is %dn", strComparing);
}
printf("Username size is %lun", sizeof(userName));
printf("Inputed username size is %lun", sizeof(userInput));
int i, j;
// printing example string
for (i = 0; i < 30; i++) {
printf("%d ", userName[i]);
}
printf("nBreak between arraysn");
// printing user inputted string, here happens something wierd
for (j=0; j < 30; j++) {
printf("%d ", userInput[j]);
}
}
Result:
Enter your text:
Alice Jane
Your text is: Alice Jane
Real text is: Alice Jane
Strings are not equal, difference is -32
Username size is 30
Inputed username size is 30
65 108 105 99 101 32 74 97 110 101 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Break between arrays
65 108 105 99 101 32 74 97 110 101 32 0 0 0 16 89 94 2 1 0 0 0 24 93 94 2 1 0 0 0
Everything goes fine, but when comparing, then strings are not equal. And when trying to print arrays, I see something weird in user input array:
65 108 105 99 101 32 74 97 110 101 32 10 0 0 16 -103 84 0 1 0 0 0 24 -99 84 0 1 0 0 0
but example array is fine, ascii encoded “Alice Jane” phrase:
65 108 105 99 101 32 74 97 110 101 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
What is wrong here and how to deal with it? Why does user input array is filled with unexpected symbols?
astralfrog is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1