如何从用户输入中分割句子(sscanf、fgets)
因此,我尝试拆分输入用户并将其分配给特定变量。用户写入的第一个输入将是大写字符,然后是空格和第二个单词 我是否正确使用fgets、sscanf分割句子? 例如,如果我写“一个红色”,一切都应该正常 如果我写“a红”,它不应该起作用,因为a不是资本 如果我写“A”,它应该打印出第二个单词没有给出。但它打印出第二个单词:(如何从用户输入中分割句子(sscanf、fgets),c,if-statement,input,scanf,fgets,C,If Statement,Input,Scanf,Fgets,因此,我尝试拆分输入用户并将其分配给特定变量。用户写入的第一个输入将是大写字符,然后是空格和第二个单词 我是否正确使用fgets、sscanf分割句子? 例如,如果我写“一个红色”,一切都应该正常 如果我写“a红”,它不应该起作用,因为a不是资本 如果我写“A”,它应该打印出第二个单词没有给出。但它打印出第二个单词:( #包括 #包括 #定义最大容量255 内部主(空){ 字符名称[最大容量]; 字符输入[MAX_CAPACITY];//用于sscanf char color[MAX_CAPAC
#包括
#包括
#定义最大容量255
内部主(空){
字符名称[最大容量];
字符输入[MAX_CAPACITY];//用于sscanf
char color[MAX_CAPACITY];//这将是句子中的第二个单词
字符字母;
printf(“输入您的姓名:”);
fgets(名称、尺寸(名称)、标准尺寸);
sscanf(名称,“%[^\n]”,名称);//要除去\n
而(1){
printf(“亲爱的%s,请输入大写字母和颜色:”,名称);
fgets(输入,sizeof(输入),标准输入);
sscanf(输入、%c%s、&字母、颜色);
//如果字母不是大写,则停止程序
如果(字母>='a'&&lettercolor
未初始化,则当sscanf()
无法读取该值时,您不能依赖color[0]
的值
您应该检查sscanf()
(和fgets()
)的返回值,以检查它们是否读取了所有预期内容
还请注意,您应该使用标准函数,而不是letter>='a'&&letter
#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;
}