[英]How to read special characters (punctuation marks, hypens, colons) using scanf function?
[英]fscanf() to read in only characters with no punctuation marks
我想從文本文件(在命令行中指定為自變量的名稱)中讀取一些單詞(在本示例中為前20個)。 在下面的代碼運行時,我發現它也帶有字符的標點符號。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]){
int wordCap = 20;
int wordc = 0;
char** ptr = (char **) calloc (wordCap, sizeof(char*));
FILE *myFile = fopen (argv[1], "r");
if (!myFile) return 1;
rewind(myFile);
for (wordc = 0; wordc < wordCap; wordc++){
ptr[wordc] = (char *)malloc(30 * sizeof( char ) );
fscanf(myFile, "%s", ptr[wordc]);
int length = strlen(ptr[wordc]);
ptr[wordc][length] = '\0';
printf("word[%d] is %s\n", wordc, ptr[wordc]);
}
return 0;
}
當我通過這句話時:“一旦獅子睡着了,一只小老鼠就開始在他身上奔跑;”“他”后面將跟一個分號。
我將fscanf()
更改為fscanf(myFile, "[az | AZ]", ptr[wordc]);
,它將整個句子作為一個單詞。
如何更改它以產生正確的輸出?
您可以接受分號,然后將其刪除,如下所示:
在將單詞存儲在ptr [wordc]中之后:
i = 0;
while (i < strlen(ptr[wordc]))
{
if (strchr(".;,!?", ptr[wordc][i])) //add any char you wanna delete to that string
memmove(&ptr[wordc][i], &ptr[wordc][i + 1], strlen(ptr[wordc]) - i);
else
i++;
}
if (strlen(ptr[wordc]) > 0) // to not print any word that was just punctuations beforehand
printf("word[%d] is %s\n", wordc, ptr[wordc]);
我尚未測試此代碼,因此其中可能有錯別字或其他內容。
或者,您可以切換
fscanf(myFile, "%s", ptr[wordc]);
對於
fscanf(myFile, "%29[a-zA-Z]%*[^a-zA-Z]", ptr[wordc]);
只捕獲字母。 29個限制字的大小,因此您不會溢出,因為您只分配30個字符的大小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.