Thread: Problem with strncpy usage

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    Problem with strncpy usage

    In this program:

    string s;
    char *c="hello";
    strncpy((char *) s.data(), c,5);
    count<<s;


    This is giving BLANK output. Where am I wrong here?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You started off on the wrong track in wanting to use strncpy to copy to an empty std::string. You could have simply written:
    Code:
    const char *c = "hello";
    string s = c;
    or even:
    Code:
    string s = "hello";
    By the way, notice that I declared c to be a const char*. You made another mistake by writing count instead of cout.

    If you want to copy a substring, then start off with a std::string, after which there are various string functions for substrings.
    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. A Problem About Usage of Bitwise Operator &
    By hefese in forum C Programming
    Replies: 5
    Last Post: 08-16-2012, 04:53 PM
  2. Strncpy problem.
    By fpsasm in forum C Programming
    Replies: 2
    Last Post: 06-15-2010, 02:47 PM
  3. Pointer usage problem.
    By Swerve in forum C++ Programming
    Replies: 11
    Last Post: 10-17-2009, 06:11 PM
  4. strncpy problem
    By -EquinoX- in forum C Programming
    Replies: 4
    Last Post: 10-18-2008, 09:10 PM
  5. Problem with template usage
    By rmullen3 in forum C++ Programming
    Replies: 2
    Last Post: 02-23-2002, 06:30 PM

Tags for this Thread