Troublesome task involving cin. functions.

closed account (ybSNAqkS)
http://www.cplusplus.com/forum/general/74224/

This link above outlines the task but I'll recap it here: Must code a program that takes a full name as input and outputs that name along with initials. The program MUST follow these rules:
* MUST use .get, .peek, .putback, and .ignore functions.
* No additional declarations aside from the 3 chars and 3 strings.
* Not allowed to use string subscript operator []. (aka Nothing array-related).
* No repetition structures.
* Must all be just within the main function (So, no recursive functions either).


I've thrown every possible thing I can think of at this puzzle, and I consider myself somewhat knowledgeable with handling the tasks at hand. I'm stumped. This is the closest I've gotten but it relies on while loops so it breaks the repetition structure rule... anyone wanna throw me a bone?

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
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string fName, mName, lName;
    char fInit, mInit, lInit;

    // Prompt for the full name and get first initial.
    cout << "Enter your full name including your middle name, each separated by a whitespace.\n";
    cin.get(fInit);
    cin.putback(fInit);

    // Form first name with the given input.
    while(!isspace(cin.peek()))
    {
        fName+=cin.peek();
        cin.ignore();
    }

    // ignore the whitespace
    cin.ignore();

    // Get the second initial
    cin.get(mInit);
    cin.putback(mInit);

    // Form middle name with the given input.
    while(!isspace(cin.peek()))
    {
        mName+=cin.peek();
        cin.ignore();
    }

    // ignore the whitespace
    cin.ignore();

    // Get the third initial
    cin.get(lInit);
    cin.putback(lInit);

    // Form last name with the given input.
    while(!isspace(cin.peek()))
    {
        lName+=cin.peek();
        cin.ignore();
    }

    cout << "Your name is: " << fName << " " << mName << " " << lName << endl;
    cout << "Your initials are: " << fInit << mInit << lInit;

    return 0;
}
Last edited on
each separated by a whitespace

From this line, I am assuming that there is only 1 whitespace character between first, middle and middle, last.

Here's a hint:

1
2
3
4
    cin.get(fInit);     // extract first initial
    cin.putback(fInit); // "put back" first initial into stream
    cin >> fName;       // extract first name
    cin.ignore();       // ignore whitespace character after first name 


Questions like this are bull.... anyway

Try to do that for the other characters as well. Let me know if you get stuck. I actually didn't need to use cin.peek(), but it's harmless to add it anywhere in the code.
Last edited on
Topic archived. No new replies allowed.