【问题标题】:How to split the sentence from user input (sscanf,fgets)如何从用户输入中分割句子(sscanf,fgets)
【发布时间】:2021-07-12 18:52:39
【问题描述】:

所以我试图拆分输入用户并将它们分配给特定的变量。用户输入的第一个输入将是大写字符,然后是空格和第二个单词。

我是否正确使用了 fgets,sscanf 来拆分句子?

例如,如果我写: "A red" ,一切都应该正常。

如果我写 "a red" ,它应该不起作用,因为 a 不是大写

如果我写“A”,它应该打印第二个单词没有给出。但它会打印出第二个单词 :(

#include <stdio.h>
#include <stdlib.h>

#define MAX_CAPACITY 255

int main(void) {
  char name[MAX_CAPACITY];
  char input[MAX_CAPACITY]; // for sscanf
  char color[MAX_CAPACITY];  // this will be the second word from the sentence
  char letter;

  printf("Enter your name: ");
  fgets(name, sizeof(name), stdin);
  sscanf(name, "%[^\n]", name);  // to get rid of \n

  while(1){
      printf("Dear %s, enter a capital letter and a color : ",name);
      fgets(input, sizeof(input), stdin);
      sscanf(input, "%c %s",&letter,color);
      
      // if letter is not capital, then stop the programm
      if (letter >= 'a' && letter <= 'z'){
        printf("Dear %s, I wish you farewell and hope to see you again soon !!!\n",name);
        break;
      }
      
      // if second word is empty, then print error message
      if(color[0] == '\0'){
        printf("Second word is not given!\n");
      }else{
        printf("Thank you, the second word is given\n");
        break;
      }
      color[0] = '\0'; // if i don't write this, program doesn't work properly, idk why
  }
  return 0;
}

【问题讨论】:

    标签: c if-statement input scanf fgets


    【解决方案1】:

    color 没有初始化,所以当sscanf() 读取失败时,你不能依赖color[0] 的值。

    您应该检查sscanf()(和fgets())的返回值,以检查它们是否读取了所有预期的内容。

    还要注意,如果没有被禁止,你应该使用标准函数islower() 而不是letter &gt;= 'a' &amp;&amp; letter &lt;= 'z'

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多