0
當我讀取字符串時,我想用''替換每個不是az或AZ或0-9的字符,但是我也不要放兩個空格連續。從文件中將文本動態地讀入字符串並刪除c中的奇數字符
我創建了下面的代碼來讀取文件中的文本,並進行清潔有點像我描述:
char *getText (FILE *file) {
bool lastWasLegal = true;
char *text, *q;
int textLength = 0;
char token;
int i = 0;
text = malloc(sizeof(char));
while ((token = getc(file)) != EOF) {
if (isLegalChar(token))
{
lastWasLegal = true;
text[i] = token;
i++;
q = realloc(text, (strlen(text) + 2) * sizeof(char));
if (!q) {
printf("Out of memory\n");
exit(1);
}
text = q;
}
else {
if (lastWasLegal)
{
text[i] = ' ';
i++;
q = realloc(text, (strlen(text) + 2) * sizeof(char));
if (!q) {
printf("Out of memory\n");
exit(1);
}
text = q;
lastWasLegal = false;
}
}
}
return text;
}
的isLegalChar
功能是:
bool isLegalChar (char a) {
if (a <= 90 && a >= 65) {
return true;
}
else if (a <= 122 && a >= 97) {
return true;
}
else if (isdigit(a)) {
return true;
}
else {
return false;
}
}
現在它有一個問題,我可以發現 - 當我的文件是:
hello,world
bye
輸出是:
世界你好再見?
但預期輸出是:
世界你好再見
(這意味着沒有問號)。
但如果文件僅僅是:
的hello world
輸出是確定的:
的hello world
要具體我試圖替換所有不是數字或數字a的字符nd將它們替換爲' '
但沒有雙空格。
我認爲這是一個內存問題,但我仍然無法找到它。
我知道帖子的名稱與我所問的問題不符,但我不確定如何命名 – Yonlif
預期的輸出是什麼? –
沒有數字或字母且不含雙字符的輸入文本''。我將編輯謝謝 – Yonlif