-3

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.

alk
  • 69,737
  • 10
  • 105
  • 255
YM_coding
  • 95
  • 8
  • 3
    In a situation like this, you should print the string that you have read to see what it contains. That's basic debugging. – klutt Nov 25 '18 at 17:42
  • 1
    `scanf` famously (yes; it is by design) separates input on spaces. – Jongware Nov 25 '18 at 17:43
  • 5
    "Standard library function X does not behave according to its documentation" is almost always a misdiagnosis. It is far more likely that the inputs are not what you think they are (as here), or even that you've misunderstood the docs. – John Bollinger Nov 25 '18 at 17:46
  • 1
    https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – klutt Nov 25 '18 at 17:51
  • Undefined behaviour is invoked, as `%s` expects a `char*`, but the code shown passes a `char**`. Anything can happen. – alk Nov 25 '18 at 18:27

3 Answers3

3

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.
Swordfish
  • 12,971
  • 3
  • 21
  • 43
1

Swordfish has already given a good answer, and fgets is preferable to scanf. However, I want to show how you would use scanf in this case:

if(scanf("%599[^\n]", input1) != 1) {
    // Handle error
}

So what is different?

  1. scanf returns the number of successfully assignments, so if this returns 1, then input1 has been assigned. If not, an error has occured.
  2. Changed s to [^\n] to read until newline
  3. Inserted 599 (one less than 600) so ensure that we don't write outside the array.
  4. Removed & from input1. In this case, it would probably work anyway, but it is undefined behavior, which should be avoided at all costs.
klutt
  • 30,332
  • 17
  • 55
  • 95
-2

Try change your scanf line from:

scanf("%s", &input1);

to:

scanf("%[^\n]", input1);

It worked out for me.