-
1 Attachment(s)
c++, code::Block
1 #include <iostream>
2 using namespace std;
3 string getInitials(string firstname, string middlename, string lastname)
4 {
5 string first, middle, last;
6 first=firstname.substr(0, 1);
7 middle=middlename.substr(0, 1);
8 last= lastname.substr(0, 1);
9 return first+middle+last;
10 }
11 int main()
12 {
13 char choice;
14 string firstName, middleName, lastName, getInitial;
15 cout<<"Enter first name: ";
16 getline(cin, firstName);
17 cout<<"Enter middle name: ";
18 getline(cin, middleName);
19 cout<<"Enter last name: ";
20 getline(cin, lastName);
21 getInitial= getInitials(firstName, middleName, lastName);
22 cout<<"Your initials are: " <<getInitial<<endl;
23 cout<<"Want more name Initials Y/N: ";
24 cin>>choice;
25 while ((choice=='y')||(choice=='Y'))
26 {
27 cout<<"Enter first name: ";
28 getline(cin, firstName);
29 cout<<endl<<"Enter middle name: ";
30 getline(cin, middleName);
31 cout<<"Enter last name: ";
32 getline(cin, lastName);
33 getInitial= getInitials(firstName, middleName, lastName);
34 cout<<"Your initials are: " <<getInitial<<endl;
35 cout<<" Want more name Initials Y/N: ";
36 cin >> choice;
37 }
38 return 0;
39 }
In the while loop of the above program line 28 is not executing and directly going to line 29. What to do so it can execute all the statements in the program.
-
Re: c++, code::Block
When posting code, please use code tags so that the code is readable. Go Advanced, select the formatted code and click '#'.
-
Re: c++, code::Block
This extracts the first char from the input stream but leaves the CR in the buffer. getline() then sees this CR as terminating the line so returns an empty string. After extracting choice from the input stream, you should then remove remaining chars using .ignore(). eg
Code:
cin >> choice;
cin.ignore(1000, '\n');
See http://www.cplusplus.com/reference/i...stream/ignore/ for more details.
Also your code is very repetitive as you basically have the same code twice - once before the while loop and once within the while loop. Why not use a do .. while loop and only have the code once within the loop?
In getInitials(), why have the extra string variables? Why not simply
Code:
return firstname.substr(0, 1) + middlename.substr(0, 1) + lastname.substr(0, 1);
-
Re: c++, code::Block
Thanks for the help. There was only the need to include ignore() statement.
-
Re: c++, code::Block
Is there any use of setter functions for the same variable in class if it is already initialized in class constructor?