這可能是我的代碼無法正常工作,但是任何空格字符(\ n,\ t,\ r等等)沒有被轉換爲空格「」。據我所知,它看起來應該可以工作,但每次碰到新線時它都會發生故障。isspace無法正常工作?
編輯:對不起,它確實將空白字符更改爲'',但在新行被擊中後停止。然後,程序會遍歷代碼,直到新的線路位置 - 它發生故障。
它也不會取代任何白色空格。
代碼繪製一個.txt文件,因此如果要運行它,請創建一個名爲alice.txt的文本文件(或者您可以更改代碼)並在文件中包含空格字符。
你能幫我嗎,我一直試圖解決這個問題幾個小時沒有用。我究竟做錯了什麼?謝謝!
#include <stdio.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define LEN 4096
void upper(char *tok, FILE *out);
void rstrip(char *tok, FILE *out);
int main()
{
char *tok; //tokenizer
char buf[LEN];
FILE *in = fopen("alice.txt", "r");
FILE *out = fopen("out.txt", "w");
int len = 0;
while (fgets(buf, LEN, in)) {
/* cleans all line breaks, tabs, etc, into space*/
while (buf[len]) {
printf("%c", buf[len]); //Error checking, prints each char of buf
if (isspace(buf[len])) //isspace not working properly? not changing \t, \r, etc to ' ' */
buf[len] = ' '; //not replacing
if (buf[len] < 0) //added cuz negative character values were being found in text file.
buf[len] = ' ';
len++;
}
/*parses by words*/
tok = strtok(buf, " ");
rstrip(tok, out);
while (tok != NULL) {
tok = strtok(NULL, " ");
rstrip(tok, out);
}
}
fclose(in);
fclose(out);
return 0;
}
/*makes appropiate words uppercase*/
void upper(char *tok, FILE *out)
{
int cur = strlen(tok) - 1; //current place
while (cur >= 0) {
tok[cur] = toupper(tok[cur]);
printf("%s\n", tok);
fprintf(out, "%s", tok);
cur--;
}
}
/*checks for 'z' in tok (the word)*/
void rstrip(char *tok, FILE *out)
{
int cur = strlen(tok) - 1; //current place
printf("%s", tok);
while (cur >= 0) {
if (tok[cur] == 'z')
upper(tok, out);
cur--;
}
}
你應該intialise變量LEN回到0第一循環結束後也開始使用調試器 – 999k 2014-11-25 06:20:11
你的第二個'strtok'(中在'rstrip'調用之後應該是'*',否則你會跳過第一個標記(並且不會正確終止循環),並且'isspace'正常工作。 – ooga 2014-11-25 06:23:44
'if(buf [len] <0)'只有當FILE * in = fopen(「alice.txt」,「r」);'失敗時纔會發生這種情況。在閱讀之前驗證文件是否已打開。 (例如'if(!in){printf(「error:open failed \ n」; return 1;}'。這樣可以防止從文本文件中讀取**奇怪的**字符。 – 2014-11-25 06:29:59