我需要检查输入是否为#34;插入WORD"其中WORD是由小写英文字母组成的非空字符串。此外,最后和单词之间可以有多个空格。我遇到了分段错误,我不知道为什么。这是代码:
void *checkInsert(char *word[100000]) {
bool ok = true;
char *w[100000];
char *nsert = "nsert";
char c;
int i = 0;
while (i < strlen(nsert) && (ok)) {
printf("%c", nsert[i]);
c = getchar();
if (nsert[i] != c) ok = false;
++i;
}
c = getchar();
if ((ok) && (c == ' ')) {
while (c == ' ') c = getchar();
}
else ok = false;
i = 0;
while (!isspace(c) && (ok)) {
if (islower(c) != 0) {
*w[i] = c;
c = getchar();
++i;
} else if (c != '\n') ok = false;
}
if (ok) {
while ((c != '\n') && (ok)) {
c = getchar();
if (c != ' ') ok = false;
}
}
if (ok) word = w;
else word = NULL;
}
答案 0 :(得分:0)
这里有一个快速编写解析空格<word>
空格<word>
#include <string.h>
#include <stdio.h>
#define FIRST "insert"
main(void) {
char c;
char *p;
char word[BUFSIZ];
memset(word, 0, sizeof(word));
for (c = getchar(); isspace(c); c = getchar()){}
p = FIRST;
while (*p) {
if (*p++ != c) {
return ;
}
c = getchar();
}
for (; isspace(c); c = getchar()){}
p = word;
while (!isspace(c) && p - word < sizeof(word) - 1) {
*p++ = c;
c = getchar();
}
printf("%s\n", word);
}
一些测试
/a.out
insert otot
otot
aurel@fat:~/dev/test$ ./a.out
sdf qsdf
aurel@fat:~/dev/test$ ./a.out
inserttoto
toto
aurel@fat:~/dev/test$ ./a.out
insert retezr
retezr
aurel@fat:~/dev/test$ ./a.out
insert toto tutu
toto
使用专用的解析功能
#include <string.h>
#include <stdio.h>
#define FIRST "insert"
void parse(char *word, size_t size) {
char c;
char *p;
for (c = getchar(); isspace(c); c = getchar()){}
p = FIRST;
while (*p) {
if (*p++ != c) {
return ;
}
c = getchar();
}
for (; isspace(c); c = getchar()){}
p = word;
while (!isspace(c) && p - word < size - 1) {
*p++ = c;
c = getchar();
}
printf("%s\n", word);
}
main(void) {
char word[BUFSIZ];
memset(word, 0, sizeof(word));
parse(word, sizeof(word));
}