operator>>
assigns to names[i]
it does not concatenate strings. You could write an overload for >>
that can concatenate strings. Would be fun but not quite appropriate here I think. Simple solution is to first read the strings, then concatenate them (I am scared of pointers, hence no pointers in my example):
std::ifstream in("filename");
std::vector<std::string> names(num);
for (int i = 0; i < num; i++)
{
in >> name[i];
std::string last_name;
in >> last_name;
name[i] += " " + last_name;
}
PS: I focused on "Is there a simple way to put two words into one index?" with minimum changes on your code. The much cleaner approach would be to define a
struct name {
std::string first_name;
std::string last_name;
};
And then in/output operators for that type. Input would be
std::istream& operator>>(std::istream& in, name& n) {
in >> n.first_name;
in >> n.second_name;
}
So that reading the two string is as simple as
name n;
std::cin >> n;
Note that all this assumes that both first_name
and last_name
do not contain whitespaces. If they do you need to use getline
or similar.
PPS: And because I think it is fun here is how you can concatenate strings via operator>>
:
#include <string>
#include <iostream>
struct concatenate_input {
std::string& parent;
};
std::istream& operator>>(std::istream& in, concatenate_input ci) {
std::string temp;
in >> temp;
ci.parent += " " + temp;
return in;
}
int main() {
std::string name;
std::cin >> name >> concatenate_input{name};
std::cout << name;
}
For input Hello World
the output is Hello World
. However, please take it with a grain of salt, it is only for illustration and I would definitely prefer the above solution. It has a quirk which is operator>>
takes the concatenate_input
parameter by value. With a (non-const) reference we could not pass temporaries which would make it much less fun.