Search code examples
ccygwin

Extended Hello World program


I'm taking my first coding class and I'm trying to figure out how to make a Hello, World! program ask for my name and then reply with it. Our instructor gave us the lines:

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
    int x;

    printf("hello, world!\n");
    printf("give me a number! ");
    scanf(" %d",&x);
    printf("%d is my favorite number!!\n",x + 1);
    return 0;
}

which is a working hello world program when compiled, but we have to make it ask for our name as well, which I cannot figure out.

This was his hint:

#include <string.h>

char s[512];                        //allocate an array to hold a string
printf("type in some stuff: ");
fgets(s,sizeof(s),stdin);           //read in a string of characters
s[strlen(s) - 1] = '\0';            //remove the newline character
printf ("you typed %s!\n", s);
//NOTE: this code fails if string is larger than 511 characters

but seeing as I know literally nothing about coding it isn't very helpful to me.

The end result is supposed to look like this when prompted with "hello"

What is your name? Fred
hello Fred
give me a number! 10
100 is my favorite number!!

Edit: I tried modelling the "what is your name?" after the "give me a number" line but it didn't work.

Edit 2: This code

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
    char s[512];

    printf("What is your name? ");
    fgets(s,sizeof(s), stdin);
    s[strlen(s) - 1] =  '\0];
    printf ("Hello %s!\n", s);
    return 0;
}

returns an error which apparently doesn't fit in the post.


Solution

  • Why can't you just change the prompt?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // This is the main function. Anything inside the { } will be run by the computer
    int main(int argc,char **argv)
    {
        char s[512]; // This will be the variable that holds the user's name (or whatever they type in)                     
        printf("What is your name? "); // Ask the user for their name
        fgets(s,sizeof(s), stdin); // Get whatever the user types in and put it in the variable s
        s[strlen(s) - 1] = '\0'; // Remove the newline character from s (what the user typed in)
        printf ("Hello %s!\n", s); // Print out "Hello" followed by whatever the user typed in (their name, which is stored in the variable s)
    
        // End the main function
        return 0;
    }
    

    Output should be

    What is your name? (User types in Fred)
    Hello Fred!