C语言中的分段错误
基本上,我希望获得用户的输入并将其标记化。例如我打字C语言中的分段错误,c,segmentation-fault,C,Segmentation Fault,基本上,我希望获得用户的输入并将其标记化。例如我打字 456 我想得到公正 4 5 6 但我的代码不起作用;( #包括 #包括 int main() { char-str; scanf(“%c”和&str); char*p=strtok(str,“\t”); while(p!=NULL){ printf(“%s\n”,p); p=strtok(空,“\t”); } } 你被char和char*搞混了 请尝试以下方法: #include <stdio.h> int main ()
456
我想得到公正
4
5
6
但我的代码不起作用;(
#包括
#包括
int main()
{
char-str;
scanf(“%c”和&str);
char*p=strtok(str,“\t”);
while(p!=NULL){
printf(“%s\n”,p);
p=strtok(空,“\t”);
}
}
你被char
和char*
搞混了
请尝试以下方法:
#include <stdio.h>
int main ()
{
char str[1000];
while(scanf("%s", str)) {
printf("%s\n", str);
}
}
#包括
int main()
{
char-str[1000];
while(scanf(“%s”,str)){
printf(“%s\n”,str);
}
}
1000是单个令牌的最大长度。请根据需要进行调整。我没有最大长度。但是char*和char的区别是什么?我知道char*是指向smth的指针…但是它的工作原理是一般的??您确定令牌没有最大长度吗?这仍然是一个可以解决的问题,但解决方案稍微长一点。
char*
是指向char
的指针。有时它只指向一个char
;有时它指向char
数组中的第一个char
。这两种情况之间的区别在于语义(即不在数据类型中)。lol这段代码似乎不起作用)道歉。重构代码时,我遗漏了一个变量名。已修复。strtok
需要字符串(char*
)作为第一个参数,而不是字符。非常基本的C概念在这里起作用…一个更基本的概念是,在字符中只能存储一个字符,您永远无法在其中填充“4\t5\t6\n”
。
#include <stdio.h>
int main ()
{
char str[1000];
while(scanf("%s", str)) {
printf("%s\n", str);
}
}