簡體   English   中英

遍歷用戶輸入並反轉C語言中的字符數組?

[英]Looping through user input and reversing character array in C?

我正在嘗試使用while循環獲取用戶輸入的字符數組(此數組的最大長度為255個字符)。 這是我到目前為止的內容,但是在輸入數據后按Enter鍵並沒有任何反應。

#include <stdio.h>

int main()
{
    char inputString[255];

    printf("Enter a line of text up to 255 characters\n");

    int i = 0;
    while(i <= 255) {
        scanf(" %c", inputString);
        i++;
    }

    // Display Reversed String
    int x;
    for(x = 255; x >= 0; --x) {
        printf("%c", inputString[x]);
    }

    return 0;
}

我是C語言的新手,不了解我的代碼有什么問題。

提前致謝。

例如:“ Hello World! ”應打印“ !dlroW olleH

除了兩件事,你幾乎都知道了

  1. c中的索引從0N - 1 ,所以代替

     int i = 0; while(i <= 255) { 

    它應該是

     for (int i = 0 ; i < sizeof(inputString) ; ++i) { 

    如您所見,循環從i == 0i == 254i < 255而不是i <= 255 反向循環也是如此,它應從sizeof(inputString) - 1254

    使用sizeof運算符時要小心。

  2. 您必須將地址傳遞給下一個字符。

     scanf(" %c", &inputString[i]); 

一個更好的方法是

int next;
next = 0;
for (int i = 0 ; ((i < sizeof(inputString) - 1) && ((next = getchar()) != EOF)) ; ++i)
    inputString[i] = next;

這接受任意長度的輸入。

#include <stdio.h>
#include <stdlib.h>

typedef struct ll {
    struct ll *next, *prev;
    char c;
} ll_t;

ll_t *
newll() {
    ll_t *rv;
    if ((rv = calloc(sizeof (ll_t), 1)) != NULL)
        return rv;      
    fprintf(stderr, "out of memory, fatal\n");
    exit(-1);
}

int 
main()
{
    ll_t *llp = newll();
    printf("Enter text to put in reverse order: ");
    while((llp->c = getchar()) != EOF) {
        if (llp->c == '\n')
            break;
        llp->next = newll();    
        llp->next->prev = llp;
        llp = llp->next;
    }
    for( ; llp != NULL; llp = llp->prev) 
        putchar(llp->c);
    putchar('\n');
}

暫無
暫無

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

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