簡體   English   中英

為什么該程序不將數組的內容打印為字符串?

[英]Why won't this program print the contents of an array as a string?

該程序應該存儲反向文本行並打印出來。 我證明了反向文本存儲在數組中,因為我可以一次將其打印出一個字符,但不會將其作為字符串打印出來。

#include <stdio.h>

//Print lines in reverse

int main()
{
    int c=0, iget=0, iprnt=0;

    char getline[1000];
    char printline[1000];

    while ((c=getchar())!='\n' && c!=EOF){
        getline[iget] = c;
        ++iget;
    }

    while (iget >= 0){
        printline[iprnt] = getline[iget];
        ++iprnt;
        --iget;
    }

    printf ("%c%c%c%c%c%c%c%c\n", printline[0], printline[1],
        printline[2], printline[3], printline[4], printline[5],
        printline[6], printline[7]);
    printf ("Result: %s\n", printline);
}

我花了很長時間,嘗試了很多事情,包括在字符串后的下一個位置添加'\\ 0'。 沒用 我很想知道為什么它不打印以及如何解決。

在第二個while循環中,您復制了太多字符,並且從輸入字符串末尾的一個字符開始。 您還需要終止printline

更改:

while (iget >= 0){
    printline[iprnt] = getline[iget];
    ++iprnt;
    --iget;
}

至:

while (--iget >= 0){                    // <<<
    printline[iprnt] = getline[iget];
    ++iprnt;
}
printline[iprnt] = '\0';                // <<<

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM