0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#include <crtdbg.h>  // needed to check for memory leaks (Windows only!)
#endif

#define FLUSH while(getchar() != '\n')

// Prototype Declarations
int readFile(FILE* ifp,char** words);

int main (void)
{
//  Local Definitions
FILE *ifp;
FILE *ofp;
char fnamer[100]="";
char **words;
int *freq;
int i;
int numWords =0;

//  Statements

    words = (char**)calloc (1001, sizeof(int));
        if( words == NULL )
        {
            printf("Error with Calloc\n");
            exit(111);
        }


  if (!(ifp=fopen("/Users/r3spectak/Desktop/song_row.txt", "r")))
  {
      printf("sucks");
      exit(100);
  }

    numWords = readFile(ifp,words);

    printf("%d", numWords);

    for(i=0;i<numWords;i++)
    printf("\n%s",words[i]);

    #ifdef _MSC_VER
    printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n");
    #endif
    printf("\n\t\tEnd of Program\n");
    printf("\n\t\tHave a great day!\n");
   return 0;

}


/*===============readFile=================
Pre:
Post:
This function
*/

int readFile(FILE* ifp,char** words)
{

// Local Variables
char buffer[1000] = " ";
int numWords = 0;

// Statements
while (fscanf(ifp," %s",buffer)!=EOF)
    {
    words[numWords] = (char*)calloc(strlen(buffer)+1,sizeof(char));
                if( words[numWords] == NULL)
                {
                    printf("\n");
                    exit(111);
                }
                strcpy(words[numWords],buffer);
                numWords++ ;
    }

return numWords;

}

输入文件包含以下内容:划船,划船,划船,顺流而下。快活快快快快快活, 人生不过是一场梦。

在 fscanf 我的数组打印之后

  Row,
    row,
    row
    your
    boat, and so on

我想要的是,

Row
row
row
your
boat

我试过 %[^,.\n] 但它不适合我。它打印垃圾

4

1 回答 1

0

您可能会发现功能特别有用。它会将您的字符串拆分为标记,例如 C 中的split()or explode()

例子:

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

int main (){
  char str[] ="Row, row, row your boat, Gently down the stream.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.");
  while (pch != NULL){
     printf ("%s\n",pch);
     pch = strtok (NULL, " ,.");
  }
  return 0;
}

我基本上复制了手册页示例。使用第一个参数作为 NULL 再次调用该函数将调出下一个字符串标记。

于 2013-03-02T07:17:00.790 回答