strtok_看看这个程序的问题,为什么不能赋值呢
来源:百度知道 编辑:UC知道 时间:2024/09/21 12:31:23
#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main(){
char st[100];//输入的字符串
char a[5][10];//将字符串按空格分割成多个字符串存放在a中
while(1){
scanf("%s",st);
char *p;
p=strtok(st," ");
strcpy(a[0],p);
int i=0;
while(p!=NULL){
puts(p);
p=strtok(NULL," ");
strcpy(a[i++],p);————这句会错阿,为什么?
}
}return 0;
}
#include<string.h>
#include<unistd.h>
int main(){
char st[100];//输入的字符串
char a[5][10];//将字符串按空格分割成多个字符串存放在a中
while(1){
scanf("%s",st);
char *p;
p=strtok(st," ");
strcpy(a[0],p);
int i=0;
while(p!=NULL){
puts(p);
p=strtok(NULL," ");
strcpy(a[i++],p);————这句会错阿,为什么?
}
}return 0;
}
因为strtok返回NULL时候,strcpy(a[i++,NULL);就出错了
加个保护
#include<stdio.h>
#include<string.h>
//#include<unistd.h>
int main()
{
char st[100];//输入的字符串
char a[5][10];//将字符串按空格分割成多个字符串存放在a中
while(1)
{
int i=0;
char *p;
scanf("%s",st);
p=strtok(st," ");
strcpy(a[0],p);
while(p!=NULL)
{
puts(p);
p=strtok(NULL," ");
if(p!=NULL)
{
strcpy(a[i++],p);//————这句会错阿,为什么?
}
else
{
return 0;
}
}
}return 0;
}
scanf("%s",st); -- 读到空白就不读了。
要用 gets 读入全行,含空白。