gpt4 book ai didi

c - 从 fputs 中分割字符串

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

#include <stdio.h>

int main()
{
FILE *fp;
char str[60];
char data[50];
char * pch;

/* opening file for reading */
fp = fopen("DATAtest.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL ) {
/* writing content to stdout */
//puts(str);
}
if( fgets (str, 60, fp)!=NULL ) {
/* writing content to stdout */
puts(str);

printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
fclose(fp);
return(0);
}

它的作用基本上是打开一个文件并从第二行提取数据。接下来应该做什么(从行: printf ("Splitting...) 开始),是将获得的文本分割成单独的字符。例如:我得到以下文本 "0 0 128 0 0 0 0 0 0 0;我想这样分割它:

0 
0
128
0
0
0
0
0
0
0

对我刚刚开始的代码感到抱歉。

最佳答案

 #include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
FILE *fp;
char str[60] = " 0 0 128 0 0 0 0 0 0 0;";//from fgets
char *data[50];//or char data[max number of parts][max of lengh of parts]
char *pch;
const char *delimiter = " ,.-;";
int i, cnt = 0;

printf ("Splitting string \"%s\" into tokens:\n",str);

pch = strtok (str, delimiter);
while (pch != NULL){
//printf ("%s\n", pch);
//strcpy(data[cnt++], pch);//by 2D array, Not necessary free.
data[cnt++] = strdup(pch);//make clone. it's not standard function.
pch = strtok (NULL, delimiter);
}
for(i = 0; i<cnt; ++i){
printf("%s\n", data[i]);
free(data[i]);//release
}
return(0);
}

关于c - 从 fputs 中分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593838/

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