Fre A
Fre A

Reputation: 11

How to combine elements of a vector in C++

Here is a sample program I am using.

while(split.good()){
            split >>first;
            split >>second;
            word=first + second;
            //cout<< static_cast<char> (word)<<endl;
            vec.push_back(static_cast<char> (word));

        }

first and second are int values. So I want to combine the elements of the vector to make a complete word.

Thanks,

Upvotes: 1

Views: 1993

Answers (2)

Tas
Tas

Reputation: 7111

First and foremost, you should heed @AliciaBytes' advice about your while loop.

To combine all your elements in your vector into a single word, you can use the following std::string constructor that takes two iterators:

template< class InputIt > basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator() );

Pass in a beginning and end iterator of your vector:

const std::string s{std::begin(vec), std::end(vec)};

This will add each element of vec into the std::string. Alternatively, you could use a for loop:

std::string s;
for (auto c : vec)
{
    // Add each character to the string
    s += c;
}

Upvotes: 1

AliciaBytes
AliciaBytes

Reputation: 7429

First off change your loop, checking for .eof() or .good() is a bad idea, see Why is iostream::eof inside a loop condition considered wrong? for more info. Instead use:

while(split >> first && split >> second)

to check that reading the values actually worked.

I misunderstood the question so the below answer isn't really what was wanted, check @Tas's answer instead.

Next I if I understand correctly you want to convert the integers into a string? It's a bit unclear but have a look at std::to_string(). Maybe you want something like:

while(split >> first && split >> second) {
    word = first + second;
    vec.push_back(std::to_string(word));
}

Upvotes: 0

Related Questions