#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


对不起,我只是从这里开始的代码。

最佳答案

您能告诉我您文件的内容吗?我用for循环替换了while循环,因为它更简洁,更容易理解:

#include <stdio.h>
#include <stdlib.h>
#include <string.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);
        for(pch = strtok(str, " ,.-"); pch != NULL; pch = strtok(NULL, " ,.-"))
        {
            puts(pch);
        }
        fclose(fp);
    }
    return 0;
}

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

10-15 06:59