gpt4 book ai didi

c - isspace 无法正常工作?

转载 作者:行者123 更新时间:2023-11-30 15:27:14 25 4
gpt4 key购买 nike

这可能是我的代码不起作用,但任何空白字符(\n、\t、\r 等)都不会转换为空格“”。据我所知,它看起来应该可以工作,但每次遇到新行时都会出现段错误。

编辑:抱歉,它确实将空白字符更改为“”,但它在新行被命中后停止。然后程序运行代码,直到新的行位置——它出现了段错误。

它也不会替换任何空格。 代码绘制在 .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--;
}
}

最佳答案

您设置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 an unsigned char or shall equal the value of the macro EOF.

关于c - isspace 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com