strcmp()不返回应返回的内容

时间:2018-11-25 17:39:14

标签: c string string-comparison strcmp

基本上,我想创建一个程序,该程序可能会在我即将举行的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!");
    }

因此,每当我被要求输入“寄存器,内存,硬盘”时,它返回1而不是0。我看不到问题。我对C有点陌生,所以很抱歉这是一个愚蠢的问题。

3 个答案:

答案 0 :(得分:2)

如注释中所述,scanf()"%s"在第一个空格字符处停止转换。要阅读整行文字,请使用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.

答案 1 :(得分:1)

剑鱼已经给出了很好的答案,fgetsscanf更可取。但是,我想说明在这种情况下如何使用scanf

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

那么有什么不同?

  1. scanf返回成功分配的数量,因此,如果返回1,则已经分配了input1。如果没有,则发生错误。
  2. s更改为[^\n]直到读到换行符为止
  3. 插入599(小于600的一个),因此请确保我们不要在数组之外进行写操作。
  4. &中删除了input1。在这种情况下,它可能仍然可以工作,但是它是未定义的行为,应不惜一切代价避免。

答案 2 :(得分:-2)

尝试从以下位置更改您的scanf行:

scanf("%s", &input1);

收件人:

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

对我有用。

相关问题