你好,我正在用fget对我的代码进行循环,我希望当用户引入"bye"这个词时,程序就会结束,所以我有一个do:
char buf[1000]
do{
fgets(buf, 1000, stdin);
//More code here
while(strcmp(buf, "bye")!=0);但是我有一个问题,当用户在写bye之前创建一个空格或一个制表符或多个空格时,strcmp不承认他为bye,所以只有当用户只键入bye而没有任何以前的space or tab时,程序才会退出。
我想知道,如果用户输入了以下内容,我如何防止by word之前的空格或制表符退出:
' bye'发布于 2020-11-08 21:11:28
fgets读取一整行,包括任何起始空格,还包括行尾的新行字符。即使用户不输入前面的空格,buf的内容也可能是"bye\n",因此在使用strcmp时,buf很难与"bye"相媲美。
我建议使用sscanf扫描缓冲区中的单个单词,然后将这个单词与"bye"进行比较。请注意,scanf("%s"...)跳过单词开头的空白字符,并在单词后面的第一个空白之前停止。
char isStopWord[20];
isStopWord[0] = '\0';
sscanf(buf,"%19s",isStopWord);
}
while(strcmp(isStopWord, "bye")!=0);发布于 2020-11-08 21:12:04
使用strcmp从数组中删除字符是非常奇怪的要求,但一切都是可能的:)
char *removeSpacesAndTabsBeginning(char *str)
{
size_t len;
char savedc;
if(str && *str)
{
len = strlen(str);
savedc = str[1];
str[1] = 0;
while(!strcmp(str, " "))
{
str[1] = savedc;
memmove(str, str + 1, len);
savedc = str[1];
str[1] = 0;
}
str[1] = savedc;
}
return str;
}
int main(void)
{
char z[] = " \t\tHello World.";
printf("`%s`\n", removeSpacesAndTabsBeginning(z));
}如果您想知道字符串是否包含"bye",请使用strstr。
int isBye(const char *str)
{
return !!strstr(str, "bye");
}发布于 2020-11-08 22:55:44
代码中有两个问题:
fgets()的返回值以检测文件的意外结束。fgets()读取的字符串,因为其他代码可能也不处理这些字符串。#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main() {
char buf[1000];
while (fgets(buf, sizeof buf, stdin)) {
size_t i = 0, length = strlen(buf);
/* trim trailing white space */
while (length > 0 && isspace((unsigned char)buf[length - 1])) {
buf[--length] = '\0';
}
/* trim leading white space */
while (isspace((unsigned char)buf[i]) {
i++;
}
if (i > 0) {
memmove(buf, buf + i, length - i + 1);
}
// check for end command
if (!strcmp(buf, "bye"))
break;
//More code here: handle other commands
//...
}
return 0;
}https://stackoverflow.com/questions/64742906
复制相似问题