gpt4 book ai didi

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

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

#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/

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