1

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,

Fre A
  • 11
  • 2

2 Answers2

1

First and foremost, you should heed @Raphael Miedl's 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;
}
Community
  • 1
  • 1
Tas
  • 6,589
  • 3
  • 31
  • 47
0

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));
}
Community
  • 1
  • 1
user1942027
  • 6,884
  • 6
  • 32
  • 44
  • Oh sorry for the confusion, "word" is really a char value, its just a bad name I gave for the char value you get from the added integer values after they are changed to char. so when that while is over what I get is a vector of char elements. I wanted to know how I can combine the char elements of the vector to make a word. sort of like vec = {'h' , 'e' , 'l' , 'l' , 'o' }; and I want a string "hello" from the vector vec. I hope this makes sense and thank you for your input. – Fre A Apr 29 '16 at 03:01
  • @FreA guess I misunderstood what you wanted to do. Anyways, @Tas answer is exactly what you want to do, just gonna leave this answer as it is for the `while` part of it. – user1942027 Apr 29 '16 at 03:07