Hello. Whenever I input a string containing spaces, it stores each word in each string variable.
#include <iostream>
using namespace std;
struct book {
string title;
string author;
int publicationYear;
};
void getInfo(book &);
void printInfo(book);
int main ()
{
book book1, book2, book3;
getInfo(book1);
printInfo(book1);
return 0;
}
void getInfo(book &BookInfo)
{
cout << "What is the title of the book?" << endl;
cin >> BookInfo.title;
cout << "Who is the author of the book?" << endl;
cin >> BookInfo.author;
cout << "When was the publication year?" << endl;
cin >> BookInfo.publicationYear;
}
The unexpected behavior is because cin stops reading when it hits a whitespace. So the first cin will only take the first word and not the other words that were given in the first cin. And the second word is read by the second cin because the second word is still in the input buffer and likewise the third word is read by the third cin. Any other residual words are left in the input buffer itself.
You can use getline like Manga mentioned, getline reads whitespaces as well, unlike cin. ;)