Sp1cyChef
Sp1cyChef

Reputation: 23

why does the cursor go to the second line after the first input

I'm trying to solve exercise 1-19 in the 2nd edition of "The C programming language"

The exercise says: Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

Here is my code

#include <stdio.h>

/* exercise 1-19 */

#define MAXLENGTH 1000

void reverse(char input[], int arraylength);

main (){
    int userinput, i;
    char inputarray[MAXLENGTH];

    i = 0;
    while ((userinput = getchar()) != EOF){
        if ( userinput == '\n' || i == (MAXLENGTH-1)){
            inputarray[i] = '\0';
            reverse(inputarray, i);
            i = 0;
        }
        inputarray[i] = userinput;
        ++i;
    }
}

void reverse(char input[], int arraylength){
    int i;
    for (i = (arraylength-1); i >= 0; --i){
        printf("%c", input[i]);
    }
}

enter image description here enter image description here

The code works but if you run it and enter the first input, the cursor doesn't go to a newline after the output. This only happens for the first output.

What is causing this? and how can I fix it?

Upvotes: 0

Views: 73

Answers (2)

alex01011
alex01011

Reputation: 1702

This line after the if statement,

inputarray[i] = userinput;

saves the newline character after you reset the index to 0. Meaning that it saves it in the first position in the array.

When you input \n for the first time, your first array element isn't '\n' but the first letter you type, therefore no newline is printed.

Also, main() should be of type int by standard. The following should do what you want:

#include <stdio.h>

/* exercise 1-19 */

#define MAXLENGTH 1000

void reverse(char input[], int arraylength);

int main (){
    int userinput, i;
    char inputarray[MAXLENGTH];

    i = 0;
    inputarray[i] = '\n'; /* place the newline character at the first position */
    ++i; /* increment i */

    while ((userinput = getchar()) != EOF){
        if ( userinput == '\n' || i == (MAXLENGTH-1)){
            inputarray[i] = '\0';
            reverse(inputarray, i);
            i = 0;
        }
        inputarray[i] = userinput;
        ++i;
    }
     return 0;
}

void reverse(char input[], int arraylength){
    int i;
    for (i = (arraylength-1); i >= 0; --i){
        printf("%c", input[i]);
    }
}

Upvotes: 0

Chris
Chris

Reputation: 36516

Consider what your reverse function is doing. You never actually print a newline character.

You may find it more useful to write your reverse function to return a reversed char * that you can then print.

Upvotes: 1

Related Questions