为什么我的编码没有读到\ n

时间:2017-06-19 19:43:55

标签: c

我正在编写一个带有句子并将其反转的代码,作为练习。这是我写的:

#include <stdio.h>

int main(void)
{
    char a, sentence[100], sign;
    char *c = sentence; 

    printf("Enter a sentence: ");

    while ( (a = getchar()) != '\n' ) 
    {
        if ( a == '?' || a == '!' || a == '.')
        {
            sign = a;
            break;
        }

        *c = a;
        c++;
    }

    for (char *d = c; d >= sentence; d--)
    {
        if ( (d == sentence) && (*d != ' ') )
        {
            for (char *a = d; a < d + 99; a++)
            {
                if ( (*a == ' ') || (*a == '\n')) //code isn't reading the \n
                {
                    break;
                }
                else
                    printf("%c", *a);
            }
        }

        if ( (*d == ' ') && (d != c) && (d != sentence + 99) )  
        {
            for (char *a = d+1; a <=  c; a++)
            {
                if ( (*a == ' ') || (a == c))
                {
                    printf(" ");
                    break;
                }
                else
                    printf("%c", *a);

            }
        }       
    }
    printf("%c\n", sign);

    return 0;
}

当我输入一个带空格的句子时,它工作正常:

  

输入一句话:这是一个句子
     句子a是这个

但是如果我输入一个没有空格的字符串,就像这样:

  

输入一个句子:Thisisasentence

我得到一个输出最初输入的内容('Thisisasentence'),然后是很多乱码输出。据我所知,这是因为代码没有进入if ( (*a == ' ') || (*a == '\n')条件。

  • 为什么编译器没有读取'\ n'

2 个答案:

答案 0 :(得分:1)

该程序可以进行一些更改 在*c = '\0';之后添加c++;以终止字符串 检查a == '\0'而不是'\n',因为while排除了'\n' 在结束时添加了一个检查,以确保不允许超过99个字符。

#include <stdio.h>

int main(void)
{
    char a, sentence[100], sign;
    char *c = sentence;

    printf("Enter a sentence: ");

    while ( (a = getchar()) != '\n' )
    {
        if ( a == '?' || a == '!' || a == '.')
        {
            sign = a;
            break;
        }

        *c = a;
        c++;
        *c = '\0';//terminate
        if ( c - sentence >= 99) {//make sure not too many characters
            break;
        }
    }

    for (char *d = c; d >= sentence; d--)//start at c and work back to sentence[0]
    {
        if ( (d == sentence) && (*d != ' ') )
        {
            for (char *a = d; !( *a == ' ' || *a == '\0'); a++)
            {
                printf("%c", *a);
            }
        }

        if ( (*d == ' ') && (d != c) && (d != sentence + 99) )
        {
            for (char *a = d+1; a <=  c; a++)
            {
                if ( (*a == ' ') || (a == c))
                {
                    printf(" ");
                    break;
                }
                else
                    printf("%c", *a);

            }
        }
    }
    printf("%c\n", sign);

    return 0;
}

答案 1 :(得分:0)

最好分成两个函数,一个用于读取一行文本,另一个用于反转它:

Enter a sentence:this is a sentence

ecnetnes a si siht

测试1

Enter a sentence:thisisasentence

ecnetnesasisiht

测试2

{{1}}