Thread: Putting integer in a string

  1. #1
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798

    Putting integer in a string

    Hi.

    I might be missing something plainly obvious here but is it possible to have the first element of a string contain the value of an integer between 0 and 255?

    What I want is to send data over TCP/IP and I want the number of bytes to be contained in the first element.

    For arguments sake, if the number of bytes in my stirng is 14 then I want to create a new string with 15 bytes. The first byte should contain the value 14.

    itoa() seems no good as it will put '1' in the first byte and '4' in the second and I want the first byte to contain '14'.

    I will then need to read this value at the other end.

    Something seems really obvious about this, but I can't seem to figure it out.

    Thanks

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >What I want is to send data over TCP/IP and I want the number of bytes to be contained in the first element.
    Code:
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    
    int main()
    {
      char buf[100];
      char msg[] = "A test";
    
      buf[0] = static_cast<char> ( sizeof msg );
      std::sprintf ( buf + 1, "%s", msg );
    
      std::cout<< static_cast<size_t> ( buf[0] ) <<std::endl;
      std::cout<< buf + 1 <<std::endl;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798
    Excellent, thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM