Thread: Can't work with full name!

  1. #1
    Registered User
    Join Date
    Jun 2018

    Can't work with full name!

    #include <stdio.h>
    #include <stdlib.h>
    #pragma warning(disable:4996)
    int main()
        char name[50];
        int year1, year2;
        int age;
        //Ask for the name
        printf("What is the name of subject?\n");
        printf("Enter name.. ");
        scanf("%s[^\n]", name);
        //Ask for the birthyear
        printf("What year did %s born?\n",name);
        printf("Enter as a 4-digit number (YYYY) : ");
        scanf("%d", &year1);
        //Ask for the target year
        printf("What is the target year?\n");
        printf("Enter as a 4-digit number (YYYY) : ");
        scanf("%d", &year2);
        age = year2 - year1;
        //Display age in target year
        printf("%s is %d years old in %d.", name, age, year2);
    This code will work with first name or last name without spaces but not with full name,help!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Try "%[^\n]" instead of "%s[^\n]". That said, when you read a string you should specify the field width, so it should be ""%49[^\n]" as name can store a string of a maximum length of 49. Unfortunately, while this would protect against buffer overflow, you would have to do more work to handle such a long input gracefully, but I suspect that's beyond the scope of what you need to do.
    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. full size of the window, full screen mode
    By nerio in forum C Programming
    Replies: 4
    Last Post: 07-20-2011, 05:25 PM
  2. Full Programs?
    By Padawan in forum C Programming
    Replies: 10
    Last Post: 04-01-2004, 09:57 PM
  3. Full Screen ?
    By slx47 in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2002, 11:55 AM
  4. Full?
    By Shakespeare in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2002, 11:04 AM
  5. Full Screen
    By JamMan in forum C++ Programming
    Replies: 3
    Last Post: 11-21-2001, 03:10 PM

Tags for this Thread