Question

Complete newbie here. 2nd day in my intro to programming class, so be gentle. We're programming in C btw.

Our assignment was to prompt the user to give us a name in the format: John Smith, and then print it back out to them like so; Smith, J.

To add to the headache the program still has to perform regardless of how many blank spaces there are. i.e. John /n Smith, John /t smith, and John /0 Smith..

Here's what I have so far,

#include <stdio.h>

int input()
{
    printf("Enter your name: \n");
    int lettest = getchar ();
    return (lettest);
}

void fname() 
{
    int lettest;
    if (lettest != EOF || '\n' || '\t' || ' ')
    {
        printf("%c.", lettest);
        lettest = getchar();
    }
    else;
}
void lname() 
{
    int lettest;
    if (lettest != EOF || '\n' || '\t' || ' ')
    {
        printf("%c.", lettest);
        lettest = getchar();
    }
    else;
}

int main () {

    input();
    lname();
    //fflush(stdin);
    fname();

    return 0;
}

My problems: I don't know how to print the last name when it's reading both from the same buffer..

Can someone explain to me how I would do my lname function??? Also, no arraylists and no string methods.

Was it helpful?

Solution

Note that in addition to the problems mentioned in other answers, expressions such as:

if (lettest != EOF || '\n' || '\t' || ' ')

do not behave as you expect them to - you need to write this particular example as:

if (lettest != EOF && lettest != '\n' && lettest != '\t' && lettest !=  ' ')

or perhaps more expressively:

if (!(lettest == EOF || lettest == '\n' || lettest == '\t' || lettest ==  ' '))

OTHER TIPS

Why don't you use scanf?

include <stdio.h>
int main() {
char f[20],l[20]; //assume a name is less then 20 letters.
printf("What is your name?\n");
scanf("%s %s",f,l);
printf("%s, %c.\n",l,f[0]);
return 0;
}

Focusing on getchar() here seems counter-productive; it reads characters and you want to read whole words (strings). Look into e.g. scanf() instead. If there is some kind of requirement that you use getchar(), you should say so in the question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top