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
- 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 == 254or- i < 255, not- i <= 255. same goes reverse loop, should start @- sizeof(inputstring) - 1or- 254.- be careful using - sizeofoperator.
- 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
Post a Comment