c - isspace 无法正常工作?

标签 c file ctype

这可能是我的代码不起作用,但任何空白字符(\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/

相关文章:

c - 前缀树中的插入和搜索实现

c - 尝试编译 TPC-H Benchmark 并返回此错误 ld : library not found for -lgcc

C++追加到字符串并写入文件

c++ - cout 是否保证有 ctype<char> 刻面?

c - 应该如何正确使用 wctype.h 函数?

C 数组行为 - 全局/局部/动态

c - 如果有条件,则为内部变量赋值 - 总是不好的做法?

C - 如何将(来自基于用户的输入)各种字符串存储在结构内的数组中?

c++ - 如何使用 fseek() 进入一行的开头