[好吧,请忍受我,因为这里有些奇怪的东西。我目前正在尝试使用最多20个char命令且没有管道等实现一个SUPER简单外壳。我也在一起学习C,因此,请原谅任何严重的错误或用法。
这是我的解析器代码:
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int running = 1;
/* Main loop */
while(running==1) {
// The max size of the input is 20 bytes
char input[20];
// Read string from user
fgets(input, sizeof(input), stdin);
/* ----- PARSE INPUT ----- */
char buffer[20];
for(int i = 0; i < sizeof(input); i++) {
buffer[i] = input[i];
/* ------ CHECK BUFFER AGAINST VARIOUS COMMANDS ----- */
// TALK TO THE HAND
if (strcmp(buffer, "TALK TO THE HAND") == 0) {
// execute TALK TO THE HAND
printf("TALK TO THE HAND\n");
}
else {
printf("WHAT DID I DO WRONG?\n");
}
}
}
}
输入TALK TO THE HAND
时的预期输出就是它的回音,但我得到的是:
TALK TO THE HAND
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
TALK TO THE HAND
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
WHAT DID I DO WRONG?
而且我不知道为什么它似乎在不同的输出中反复循环。
代码迭代太远
迭代到字符串的长度,而不是缓冲区的大小。
// for(int i = 0; i < sizeof(input); i++) {
for(int i = 0; input[i]; i++) {
无论如何,都不需要此迭代。只需比较input
//if (strcmp(buffer, "TALK TO THE HAND") == 0) {
if (strcmp(input, "TALK TO THE HAND") == 0) {
不考虑已读取的'\n'
。
圈闭电位'\n
'
fgets(input, sizeof(input), stdin);
// add
input[strcspn(input, "\n")] = '\0';
缓冲区太小
[buffer[]
需要容纳20个字符,'\n'
和'\0'
。
// char input[20];
char input[20 + 1 + 1];
高级
[fgets()
可能返回NULL
,这表明stdin
已关闭。
用户输入的文本可能太多,很容易检测到
#define INPUT_N 20
// extra \n \0
char input[INPUT_N + 1 + 1 + 1]; // I'd just go with INPUT_N*2
if (fgets(input, sizeof(input), stdin) == NULL) {
fprintf(stderr, "Input closed\n");
return EXIT_FAILURE;
}
size_t len = strlen(input);
if (len > 0 && input[len-1] == '\n') {
input[--len] = '\0'; // lop off \n
}
if (len > INPUT_N) {
// exit or otherwise cope with too much data
fprintf(stderr, "Excessive long input\n");
return EXIT_FAILURE;
}
...