Thread: Help with basic i/o please

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    1

    Help with basic i/o please

    Hello, I am a beginner in C programming and would like help with this small piece of code. It is supposed to ask you your name and then repeat it back to you:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main() {
        char (num);
        printf("Hello, what is your name? ");
        scanf("%d" ,&num);
        printf("Hello %d.", num);
    }
    When executing the program, it just says "Hello, 0" when you type in letters. when you type in numbers it says hello and then the number.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This is not what you want:
    Code:
    char (num);
    You want to store a name, so you need to store a string, not a single char. Furthermore, the parentheses are unnecessary. What you could do is to decide on a maximum length for the name, and then declare an array one more than that length (for the null character), e.g.,
    Code:
    char name[50];
    Then you use %s with a field length to read the name:
    Code:
    if (scanf("%49s", name) == 1) {
        /* ... */
    }
    In the above code snippet, I used 49 since that is the maximum length for the name. I also checked that scanf returned 1, otherwise there must have been some kind of input error.

    Oh, and then remember to print using %s, not %d, since you have a string.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with the basic's
    By clb2003 in forum C Programming
    Replies: 2
    Last Post: 02-09-2009, 02:40 AM
  2. C++ basic
    By artoke in forum C++ Programming
    Replies: 8
    Last Post: 04-28-2007, 02:20 PM
  3. basic ms-dos sim, need help
    By JOlszewski in forum C++ Programming
    Replies: 1
    Last Post: 01-13-2006, 03:55 PM
  4. vc++ basic help
    By gooddevil in forum C++ Programming
    Replies: 2
    Last Post: 05-16-2004, 11:01 AM
  5. m$vc++6 basic help
    By CobraCC in forum C++ Programming
    Replies: 4
    Last Post: 03-29-2003, 04:41 PM

Tags for this Thread