我必须拆分一个字符串输入值,其中有一个空格并输出结果。在数组中拆分字符串值
例如:输入:
I am a noob at C
输出:
>>I
>>am
>>a
>>noob
>>at
>>C
代码:
void splitText(){
char str[100];
char sep[] = " \r\n";
char *res; //if i remove this
fgets(str,sizeof str,stdin);
if (fgets(str, sizeof str, stdin) == NULL) {
printf("error");
}
char *p = strchr(str, '\n');
if (p) *p = 0;
res = strtok(str, sep); //and this
printf("%s\n",res); //and change this to str
}
工作码的人遇到了同样的问题:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void splitText() {
char str[100];
char sep[] = " \n";
char *res;
fgets(str,sizeof str, stdin);
if (fgets(str, sizeof str, stdin) == NULL) {
printf("Error");
break;
}
res = strtok(str, sep);
while(res != NULL){
printf("Splitted String: \"%s\"\n",res);
res = strtok(NULL,sep);
}
}
感谢大家帮助我解决这个问题!
'焦炭海峡[100] =的scanf( “%s” 时,STR);',你在哪里读的? – Haris
'scanf()'返回一个整数,并且将它分配给一个char数组 'scanf(“%s”,str)'将完成您的工作,只需删除左侧部分 –
无论何时您对特定函数去阅读它。学习函数返回什么或在这种情况下它如何存储值可能会节省您很多时间和麻烦 – Talaria