Thread: Assign part of char array to vector

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Assign part of char array to vector

    I would like to put only 'World' into a string or vector.
    Is it possible without a for loop?

    Code:
    int main()
    {
        string Data;
        char buf[] = "Hello World";
        for(int i=6; i< 12; i++)
        {
            Data[i] = buf[i];
            cout << "Data: " << Data[i] << endl;
        }
        cout << "Data: " << Data << endl;
    
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    e.g.
    Code:
    char buf[] = "Hello World";
    string Data(&buf[6]);
    kurt

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Awesome, thank you Zuk.
    And would it be possible to put only from 6 to 8 in the string?
    Because I want to put a binary string in it that doesn't have terminating NULL at the end.
    Using Windows 10 with Code Blocks and MingW.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    #include <vector>
    #include <iostream>
    
    int main() {
       char buffer[] = "Hello World";
       std::vector<char> v(&buffer[6], &buffer[9]);
       for(  size_t i = 0; i < v.size(); ++i ) {
          std::cout << v[i] << ",";
       }
       std::cout << std::endl;
     }
    Kurt

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Great, thanks!
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do I assign a char array to an int array?
    By mark 555 in forum C Programming
    Replies: 7
    Last Post: 12-13-2012, 10:24 PM
  2. Replies: 3
    Last Post: 10-03-2012, 01:23 AM
  3. Weird problem with an array of vector<char *>'s ???
    By phummon in forum C++ Programming
    Replies: 2
    Last Post: 05-02-2010, 05:39 PM
  4. Assign value of multiple char array elements to int
    By 3saul in forum C Programming
    Replies: 3
    Last Post: 02-03-2006, 05:31 AM
  5. Vector & char array problems. :-(
    By rjcarmo in forum C++ Programming
    Replies: 2
    Last Post: 05-19-2003, 08:24 PM