简体   繁体   中英

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). Here is what I have so far, but nothing happens once I press enter after entering data.

#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.

Thanks in advanced.

Eg: " Hello World! " should print " !dlroW olleH "

You almost got it except for two things

  1. The indices in c go from 0 to N - 1 , so instead of

     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 . The same goes for the reverse loop, it should start at sizeof(inputString) - 1 or 254 .

    Be careful using the sizeof operator.

  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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM