user3340001
user3340001

Reputation: 237

Are the values of cin held somewhere?

Write the definition of a function named copy that reads all the strings remaining to be read in standard input and displays them, one on a line with no other spacing, onto standard output. Do not use loops of any kind (for, while, etc.).

I've tried something like:

void copy()
{
    string x;
    getline(cin, x);
    cout << x << "\n";
    if(cin){
        copy();
    }
    else{
        return;
    }
}

But I may not be understanding entirely what "all the string remaining to be read in standard input" means. Can someone help me out?

Upvotes: 2

Views: 1052

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106096

void copy()
{
    { // create a scope...
        string x;
        if (getline(cin, x))
            cout << x << "\n";  // don't output 'x' when getline fails!
    } // let x go out of scope - less baggage during recursion...
    if(cin)
        copy();
}

The question's a bit vague...

...reads all the strings remaining to be read in standard input and displays them, one on a line with no other spacing, onto standard output.

Is a "string" necessary the same as a line? One reason I suspect not is because if it is, the question's even less interesting (and you didn't think it possible!) - a reasonable answer:

std::cout << std::cin.rdbuf();

Another reason is "no spacing"... perhaps that's referring to leading and trailing space on each line, or maybe the intention was that each space separated value be considered a string, in which case you'd need:

void copy()
{
    {
        string x;
        if (cin >> x);
            cout << x << "\n";
    }
    if (cin)
        copy();
}

Anybody's guess which is wanted....

Upvotes: 0

AJG85
AJG85

Reputation: 16197

Recursion is the right idea to satisfy teacher's strange limitations however look into std::getline and the operators and methods of std::cin for correct usage if you'd like to store the input in variables etc. Currently the value read is being stored in the temporary string named x for each scope of the function call on stack.

Edit: There is nothing particularly wrong with what you have although you technically don't need the else case as the stack will unwind after last call to copy(); and since it's a void function no return is necessary.

Upvotes: 1

Related Questions