【发布时间】: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