Trying to concatenate elements of string vector into a string

Feb 17, 2016 at 10:15pm
I have vector<string> fruits where each element is a string of a fruit name. I want to take each element and concatenate into a string called fruitylicious (ex. "applebananastrawberry") When I do

1
2
3
4
5
6
  vector <string> fruits;    //I have a while loop that `cin`s strings to put into elements--this is working as expected
string fruitylicious = "";
    for(int i=0;i<fruits.size();i++){
                        fruitylicious += fruits.at(i);
                    }
    cout << fruitylicious << endl;


I get a bunch of errors on compilation (otherwise, the rest of the program compiles and behaves as expected if I comment this part out).
What's the problem?
Last edited on Feb 17, 2016 at 10:29pm
Feb 17, 2016 at 10:21pm
For starters, your vector is called fruits not fruit.

for(int i=0;i<fruit.size();i++){ // missing an s after fruit

And that's about it really -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {

	std::vector <string> fruits = { "Apple", "Bapple", "Sapple" };  
	string fruitylicious = "";

	for (int i = 0; i<fruits.size(); i++){
		fruitylicious += fruits.at(i);
	}
	cout << fruitylicious << endl;

	
	return 0;
}
Last edited on Feb 17, 2016 at 10:22pm
Feb 17, 2016 at 10:23pm

I get a bunch of errors on compilation
(otherwise, the rest of the program compiles and behaves as expected if I comment this part out).
What's the problem?


Read the errors. They're there for a reason.
Feb 17, 2016 at 10:30pm
.
Last edited on Feb 17, 2016 at 10:51pm
Feb 17, 2016 at 10:39pm
Errors. Start at the top. It's complaining about this line:

cout << "hand: " << hand << endl;

It says it doesn't know what to do with the << and hand.

Given that hand is an object of type vector<string>, and that the operator << doesn't know what to do with a vector<string>, this seems pretty clear.

<< does know about string objects. It doesn't know about vector<string> objects.

Perhaps you meant cout << "hand: " << hands << endl;
Last edited on Feb 17, 2016 at 10:40pm
Feb 17, 2016 at 10:48pm
Wow, a single typo messed me up. I immediately disregarded the errors because there were several pages of it. Thank you and sorry for the stupid mistake.
Topic archived. No new replies allowed.