Looping through user input and reversing character array in C? -


i trying user's input while loop character array (this array can have maximum length of 255 characters). here have far, nothing happens once press enter after entering data.

#include <stdio.h>  int main() {     char inputstring[255];      printf("enter line of text 255 characters\n");      int = 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 new c , don't understand wrong code.

thanks in advanced.

eg: "hello world!" should print "!dlrow olleh"

you got except 2 things

  1. the indices in c go 0 n - 1, instead of

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

    it should be

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

    as can see loop goes i == 0 i == 254 or i < 255 , not i <= 255. same goes reverse loop, should start @ sizeof(inputstring) - 1 or 254.

    be careful using sizeof operator.

  2. you have pass address next character.

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

a better way be

int next; next = 0; (int = 0 ; ((i < sizeof(inputstring) - 1) && ((next = getchar()) != eof)) ; ++i)     inputstring[i] = next; 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -