检查角色是否是空格

时间:2013-03-10 19:47:23

标签: c

我在C中创建了一个荒谬简单的程序来处理getchar()。该程序将打印出您输入的内容,直到您按Enter键,它将保证您的行每行不超过80个字符。为此,我保持已输入的字符数的运行计数。一旦char计数达到70,遇到的下一个空格将导致换行。如果在70-80之间没有遇到空格,则无论如何都会发生换行。我意识到这是一个超级天真的实现,可以左右优化,但请记住,我只是搞乱:

while ((c = getchar()) != '\n') {
    if (lineLengthCount < 70) {
        putchar(c);
        lineLengthCount++;
    }   
    else if (lineLengthCount < 80 && (c == ' ')) {
        printf("%c\n", c); 
        lineLengthCount = 0;
    }   
    else {
        printf("%c\n", c); 
        lineLengthCount = 0;
    }   
}   

问题是c == ' '条件似乎没有实际检查空间。我得到这样的输出:

fitter happier more productive comfortable not drinking too much regula
r exercise at the gym three days a week getting on better with your ass
ociate employee contemporaries at ease eating well no microwaved dinner

我希望在遇到空格时会截断这些行。相反,无论在第70行之后输入什么字符,都会创建一个新行。我错过了什么吗? ' '真的意味着任何角色吗?

4 个答案:

答案 0 :(得分:5)

while ((c = getchar()) != '\n') {
    if (lineLengthCount < 70) {
        putchar(c);
        lineLengthCount++;
    }   
    else if (lineLengthCount < 80 && (c == ' ')) {
        printf("%c\n", c); 
        lineLengthCount = 0;
    }   
    else if (lineLengthCount >= 80){
        printf("%c\n", c); 
        lineLengthCount = 0;
    }
    else{
        putchar(c);
        lineLengthCount++;
    }
}

我认为这应该有效。当少于80个字符但字符不是空格时,这应该阻止else执行。

编辑:我现在意识到,如果lineLengthCount小于80但字符不是空格,则根本不会打印,所以我在末尾添加了另外一个来修复它。

这不会更简短,更简洁吗?

while ((c = getchar()) != '\n') {
    putchar(c);
    if((c == ' ' && lineLengthCount >= 70) || lineLengthCount >= 80){
        printf("\n");
        lineLengthCount = 0;
    }
    else
        ++lineLengthCount;
}

答案 1 :(得分:4)

您的情况有问题:如果lineLengthCount是&gt; 70但下一个字符不是空格,最后else将被击中,打破行并重置计数器。

答案 2 :(得分:1)

如果你完全不确定发生了什么,我会建议将“if”条件分解为三个明确的检查:

while ((c = getchar()) != '\n') {
    lineLengthCount++;
    if (lineLengthCount < 70) {
        putchar(c);
    }   

    if (lineLengthCount < 80 && (c == ' ')) {
        printf("%c\n", c); 
        lineLengthCount = 0;
    }   

    if (lineLengthCount == 80) {
        printf("%c\n", c); 
        lineLengthCount = 0;
    }   
}   

如果你想看看发生了什么,请在每个“if”中写一些调试输出,以便注意它何时被调用。

一旦它起作用,并且你理解了原因,你可以将其编辑并组合“ifs”......

答案 3 :(得分:1)

使用''完全有效。您还可以尝试使用C标准库函数isspace()来检查字符是否为空格。此函数返回一个布尔表达式,如:

char ch = '0';

if (isspace(ch))
    //the char is a space...

通过'is space',这个函数实际上意味着任何'空格'字符,因此包含'\ n'或任何其他打印为空格的字符。

您还可以使用十进制值32,这意味着与空格相同:

if (ch==32)

但为了便于阅读,我宁愿使用第一个版本!

相关问题