![](/img/trans.png)
[英]How to read only integers from a file with strings, spaces, new lines and integers in C
[英]How to read integers from file with integers and strings in C
我正在讀取一個.txt 文件,其中包含隨機形式的數據,即其中包含混合的整數和字符串。
示例.txt
文件:
this is a 22 string 33 sorry222 stack33ing
still yysi288 2nd line
我想讀取文件並區分所有有效字符串,即不包含與它們連接的整數。 並將這些字符串存儲在一個數組中。
關於如何區分的任何線索?
您可以為此目的使用#include <ctype.h>。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int checkString( const char s[] ) {
unsigned char c;
while ( ( c = *s ) && ( isalpha( c ) || isblank( c ) ) ) ++s;
return *s == '\0';
}
void printNonNumericWords(char str[]) {
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
while(ptr != NULL)
{
if (checkString(ptr))
printf("'%s'\n", ptr);
ptr = strtok(NULL, delim);
}
printf("\n");
}
像這樣撥打 function。
printNonNumericWords(this is a 22 string 33 sorry222 stack33ing");
第一:我不能為你寫程序。 這是您的任務,除此之外,我什至無法更改您的代碼或至少建議更改,因為您沒有提供任何代碼。 對於這種情況,我只能給你一個塵土飛揚的領先算法:
您可能看到的所有單詞都不是文件中的有效字符串。 它只是一個在每個字符序列之間包含空格字符的字符串,這些字符以一個單詞或分隔字符串的形式出現,但事實並非如此。
您必須首先從文件中獲取整個字符串並將其存儲到一個char
數組中,讓我們將其命名為source
,使用fgets()
:
#include <stdio.h>
FILE *input;
char source[200];
input = fopen("text.txt","r");
fgets(source, 200, input);
之后,您需要通過將源字符串的每個字符一個接一個地傳輸到其他char
arrays 來制作這些“單詞”分隔的字符串,並在空格字符或 NUL 字節之后立即停止向它們寫入字符最后一個詞在源字符串中提供。 不要忘記使用 Nul-Byte (\n) 來終止每個字符串。
此后,您檢查每個現在有效且分隔的字符串,如果它是包含數字的字符串或沒有任何數字的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.