isspace无法正常工作?
这可能是我的代码无法正常工作,但是任何空格字符(\ 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--;
}
}
除验证您的FILE *streams
已打开之外,还需要验证传递到您的函数的值。当strtok
完成标记化时,它将返回NULL
。你不想通过NULL
到rstrip
。例如:
void rstrip(char *tok, FILE *out)
{
if (!tok) return; // validate tok
int cur = strlen(tok) - 1; //current place
您需要为upper
做同样的事情。简单地解决这些问题是很长的路要走。
$ cat alice.txt
#include <stdio.h>
int func()
{
z z z z z
}
int main(void)
{
printf("%d\n",func());
return 0;
}
输出:
$ ./bin/ctypehelp
#include <stdio.h>
#include<stdio.h>int func()
intfunc(){
{ z z z z z
zZ
zZ
zZ
zZ
zZ
}
}int main(void)
intmain(void){
{ printf("%d\n",func());
printf("%d\n",func()); return 0;
return0;}
out.txt:
$ cat out.txt
ZZZZZ
掺入由J.L。:
输入建议的验证和更改后
处理这些改进,并在您再次卡住时回发。
您在错误的地方设置了len = 0;
。
您需要:
while (fgets(buf, LEN, in) != 0)
{
for (int len = 0; buf[len] != '\0'; len++)
{
printf("%c", buf[len]);
if (isspace((unsigned char)buf[len]))
buf[len] = ' ';
if (buf[len] < 0)
buf[len] = ' ';
}
…rest of loop…
}
这可以确保您所设置的读取每一行len
为0。您还需要确保isspace()
的参数有效 - 这意味着它是一个int
并且必须是EOF或对应于unsigned char
的值。
C标准说(指论据,is*()
功能<ctype.h>
:
In all cases the argument is an
int
, the value of which shall be representable as anunsigned char
or shall equal the value of the macro EOF.
@RolandIllig:是的;修正的。 – 2016-09-18 03:16:44
你应该intialise变量LEN回到0第一循环结束后也开始使用调试器 – 999k 2014-11-25 06:20:11
你的第二个'strtok'(中在'rstrip'调用之后应该是'*',否则你会跳过第一个标记(并且不会正确终止循环),并且'isspace'正常工作。 – ooga 2014-11-25 06:23:44
'if(buf [len] 2014-11-25 06:29:59