Basically I want to create a program that would have potential questions that might be in my upcoming exam in Digital Systems.
#include <stdio.h>
#include <string.h>
int main() {
char input1[600];
printf("What is the set of available registers?");
scanf("%s", &input1);
if(strcmp(input1, "registers, memory, hard disc") == 0){
printf("Good job! You got it right");
}
else {
printf("Wrong answer!");
}
So whenever I type "registers, memory, hard disc" when I'm asked it returns 1 instead of 0. I cannot see the problem. I am kind of new to C so sorry if it is a silly question.
As already said in the comments, scanf()
with "%s"
stops conversion at the first whitespace character. To read a whole line of text, use fgets()
:
#include <stddef.h>
#include <stdio.h>
#include <string.h>
// ...
char foo[100];
if(!fgets(foo, sizeof(foo), stdin)) // don't use sizeof on pointers
; // handle error // for that purpose!
size_t length = strlen(foo);
if(length && foo[length - 1] == '\n') // fgets also reads the newline character
foo[--length] = '\0'; // at the end of the line, this removes it.