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 .

void copy()
{
    string x;

    if(cin >> x)
    {
        if(cin != '\n')
        {
            copy()
        }
    return (x +1);
    }

    cout << x <<endl;
}

Recommended Answers

All 6 Replies

Let's see if you can determine the problems with these two lines:

void copy()

and

    return (x +1);

then figure out what it implies for

            copy()

(Bonus points if you can see the syntax error in that last line.)

Well I have return as void and I am attempting to return an integer of some sort.
There is no semicolon after copy().

void copy()
{
    string x;
    if(cin >> x)
    {
        if(cin != '\n')
        {
            copy();
        }
    return;
    }
    cout << x <<endl;
}

Just ran that code.. still not working. I think I am missing something. I am trying to recursively call cin to read a set of strings such as "Here comes the sun" and then output the string. Really not sure where I am going wrong.

I'm going to recommend two things: first, that you change the return type to string and second, that you declare a char ch. If you then take the return value, and append x to it:

string copy()
{
    cin >> ch; 

    if(ch != '\n')
    {
        return ("" + ch + copy());
    }
    else
    {
        return "";
    }
}   

then it should fall into place.

I can't have it return a string. This is being done in my programming lab (which is horrible) and I can't change that.

#include <iostream>
using namespace std;
void copy();
//The above code is what is inside my programming lab
void copy
{
    string word;
    cin>>word;
    x=x+word+" ";

    if(cin.fail())
    {
       cout << x << endl;
       return;
    }
}

I tried it this way to no avail.

void copy ()
{
    string x;



    if(cin >> x)
    {
    cout << x <<endl;
    return(copy());
    }
}

Ashley I would rewrite your last post as

void copy()
{
    string x;
    // do I still have input?
    if (cin >> x)
    {
        cout << x << endl
        copy();
    }
    // if no input remains return
    return;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.