gpt4 book ai didi

c - 读取 C 中的输入时出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:15:42 25 4
gpt4 key购买 nike

我需要检查输入是否采用“插入 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;
}

最佳答案

这里是一个解析空格的快速程序 <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));
}

关于c - 读取 C 中的输入时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com