这可能是我的代码无法正常工作,但是任何空格字符(\ 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