如何在C中提取单词后的字符串
How to extract the string after a word in C
我正在尝试在我的程序中添加一个功能,以获取 C 中特定单词后的特定单词或句子。
例如
当我尝试输入时:
“say Hello World”,程序只会打印“Hello World”。
我的代码是这样运行的:
int main(){
char command;
do{
printf("MyOS>");
scanf("%s", &command);
if(strncmp(&command, "say", 3) == 0){
//enter code here
}
} while (strncmp(&command, "exit", 4));
return 0;
}
当运行时,程序要求输入字符串,如果我的字符串以“say”开头,我希望它输出下一个words/string。
你有两个问题
scanf("%s", &command);
这里变量 command
需要一个大于 1 的缓冲区。
使用如下
#define COMMAND_SIZE 1024
并声明一些类似 char command[COMMAND_SIZE] = {0}
的东西
- 我认为您正在尝试读取多字字符串,即使命令有足够的大小,您使用的方式也无法做到这一点
scanf("%s", command);
。
最好使用 fgets(command, sizeof(command), stdin);
来阅读多字串。
简而言之,您需要这样的东西:
#include <stdio.h>
#include <string.h>
#define COMMAND_SIZE 512
int main(){
char command[COMMAND_SIZE] = {0};
do{
printf("MyOS>");
fgets(command,sizeof (command), stdin);
if(strncmp(command, "say", 3) == 0) {
printf(" %s\n", command+3);
}
} while (strncmp(command, "exit", 4));
return 0;
}
注意:请确保您分配足够的缓冲区来存储您的输入命令,并输入少于COMMAND_SIZE
个字符的输入,以便它有足够的space \n
,否则您将面临剩余 \n
个字符的问题。
我正在尝试在我的程序中添加一个功能,以获取 C 中特定单词后的特定单词或句子。
例如 当我尝试输入时: “say Hello World”,程序只会打印“Hello World”。
我的代码是这样运行的:
int main(){
char command;
do{
printf("MyOS>");
scanf("%s", &command);
if(strncmp(&command, "say", 3) == 0){
//enter code here
}
} while (strncmp(&command, "exit", 4));
return 0;
}
当运行时,程序要求输入字符串,如果我的字符串以“say”开头,我希望它输出下一个words/string。
你有两个问题
scanf("%s", &command);
这里变量command
需要一个大于 1 的缓冲区。
使用如下
#define COMMAND_SIZE 1024
并声明一些类似 char command[COMMAND_SIZE] = {0}
- 我认为您正在尝试读取多字字符串,即使命令有足够的大小,您使用的方式也无法做到这一点
scanf("%s", command);
。
最好使用 fgets(command, sizeof(command), stdin);
来阅读多字串。
简而言之,您需要这样的东西:
#include <stdio.h>
#include <string.h>
#define COMMAND_SIZE 512
int main(){
char command[COMMAND_SIZE] = {0};
do{
printf("MyOS>");
fgets(command,sizeof (command), stdin);
if(strncmp(command, "say", 3) == 0) {
printf(" %s\n", command+3);
}
} while (strncmp(command, "exit", 4));
return 0;
}
注意:请确保您分配足够的缓冲区来存储您的输入命令,并输入少于COMMAND_SIZE
个字符的输入,以便它有足够的space \n
,否则您将面临剩余 \n
个字符的问题。