KhanhThan1002
KhanhThan1002

Reputation: 55

Unable to display expected result using putchar(ch)

I am new to C programming :D.

This is the Programming Project 7.1 in C Programming - A Modern Method. For example, the input first and last name are Lloyd Fosdick, the expected result should be Fosdick, L. I tried counting the number of characters in the first name (which is 5 in this case). Then, when i > the length of the first name, start printing by using putchar(), as illustrated by the code below.

#include <stdio.h>
int main(void)
{
    char ch, first_ini;
    int len1 = 0, i = 0;
    printf("Enter a first and last name: ");
    ch = getchar();
    first_ini = ch;
    printf("The name is: ");
    while (ch != ' '){
        len1++;
        ch = getchar();
    }
    while (ch != '\n')
    {
        i++;
       if (i <= len1) {
            ch = getchar();
        }
        else {
            putchar(ch);
            ch = getchar();
        }

    }
    printf(", %c", first_ini);
    return 0;
}

The result I got was ick, L. instead of Fosdick, L

Upvotes: 1

Views: 65

Answers (1)

Adarsh Anurag
Adarsh Anurag

Reputation: 660

You should try the following changes to your code.

#include <stdio.h>
int main(void)
{
    char ch, first_ini;
    int len1 = 0, i = 0;
    printf("Enter a first and last name: ");
    ch = getchar();
    first_ini = ch;
    printf("The name is: ");
    while (ch != ' '){
        len1++;
        ch = getchar();
    }
    while (ch != '\n')
    {
        ch = getchar();// get the characters of second word
        if(ch != '\n')
            putchar(ch);// print the characters of second word but avoid newline
    }
    printf(", %c", first_ini);
    return 0;
}

The problem with your code was that it started printing the characters of second word only when the length of second word became greater than the first word.

Upvotes: 2

Related Questions