Strings not functioning properly

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;
}

void printInfo(book Info)
{
cout << "Title: " << Info.title << endl;
cout << "Author: " << Info.author << endl;
cout << "Publication year: " << Info.publicationYear << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

 using namespace std;

 struct book {
 string title;
 string author;
 int publicationYear;
 };



 void getInfo(book &);
 void printInfo(const 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;
 getline(cin, BookInfo.title);
 cout << "Who is the author of the book?" << endl;
 getline(cin, BookInfo.author);
 cout << "When was the publication year?" << endl;
 cin >> BookInfo.publicationYear;
 }

 void printInfo(const book &Info)
 {
 cout << "Title: " << Info.title << endl;
 cout << "Author: " << Info.author << endl;
 cout << "Publication year: " << Info.publicationYear << endl;
 } 
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. ;)
Last edited on
Topic archived. No new replies allowed.