c - 如何通过省略逗号来读取带逗号的字符串 %[^,] 不适合我

标签 c arrays string scanf calloc

#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] 但它对我不起作用。它打印垃圾

最佳答案

您可能会发现this功能特别好用。它将把你的字符串分割成标记,就像 C 语言中的 split()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 再次调用该函数将显示下一个字符串标记。

关于c - 如何通过省略逗号来读取带逗号的字符串 %[^,] 不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15171451/

相关文章:

java - 如何用空格字符将一个字符串拆分为另一个字符串?

java - 删除所有非数字字符,包括句点

c - 带有 Redis 事件循环的 HTTP 服务器

arrays - Golang 字节数组通过 channel 通信丢失数据

c - 如何打印 5 位访问代码的 32 种不同组合(每个数字有 2 个选择(2^5))?

javascript - ionic 显示阵列导致模板

c - 查找二维数组中的重复元素

c++ - 对字符串指针数组进行排序

c - 重新编码 printf; .h 文件 : compiler doesn't recognise the va_list type 中的错误

python - 查找由 python 脚本调用的出现段错误的 C 模块行