简体   繁体   English

遍历用户输入并反转C语言中的字符数组?

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

I am trying to get a user's input with a while loop as a character array (this array can have a maximum length of 255 characters). 我正在尝试使用while循环获取用户输入的字符数组(此数组的最大长度为255个字符)。 Here is what I have so far, but nothing happens once I press enter after entering data. 这是我到目前为止的内容,但是在输入数据后按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;
}

I am new to C and don't understand what is wrong with my code. 我是C语言的新手,不了解我的代码有什么问题。

Thanks in advanced. 提前致谢。

Eg: " Hello World! " should print " !dlroW olleH " 例如:“ Hello World! ”应打印“ !dlroW olleH

You almost got it except for two things 除了两件事,你几乎都知道了

  1. The indices in c go from 0 to N - 1 , so instead of c中的索引从0N - 1 ,所以代替

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

    it should be 它应该是

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

    as you can see the loop goes from i == 0 to i == 254 or i < 255 and not i <= 255 . 如您所见,循环从i == 0i == 254i < 255而不是i <= 255 The same goes for the reverse loop, it should start at sizeof(inputString) - 1 or 254 . 反向循环也是如此,它应从sizeof(inputString) - 1254

    Be careful using the sizeof operator. 使用sizeof运算符时要小心。

  2. You have to pass the address to the next character. 您必须将地址传递给下一个字符。

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

A better way to do this would be 一个更好的方法是

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

This accepts arbitrary length input. 这接受任意长度的输入。

#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