【问题标题】:how to read strings with commas by omitting them %[^,] not working for me如何通过省略逗号来读取带逗号的字符串 %[^,] 不适合我
【发布时间】:2013-03-02 06:19:01
【问题描述】:
#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] 但它不适合我。它打印垃圾

【问题讨论】:

  • 那么您是否尝试用逗号分隔输入字符串?
  • 您不需要在 C 程序中强制转换 calloc() 的返回值。
  • @H2CO3 我试图根本不阅读逗号。
  • @CarlNorum 我不明白你的意思。
  • @KexyKathe Carl Norum 的意思是this.

标签: c arrays string scanf calloc


【解决方案1】:

您可能会发现this 函数特别有用。它会将您的字符串拆分为标记,例如 split()explode() 的 C 等效项。

例子:

#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-04-02
    • 2011-06-26
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多