uwu
uwu

Reputation: 59

How do I use the enter key to create new line, rather than inputting string?

I have to write a program that allows the user to enter a multiline poem, pressing the enter key to create a new line in the poem. All lines of the poem need to be stored in a single string, and I'm not sure how to concatenate the "\n" to user input. Additionally, once the user is done with the poem, I'm not sure how to then move on and execute further code in the program.

Here is the code I have so far:

/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/

#include <string>
#include <iostream>
using namespace std;

void makePoem()
{
    string user_input;
    cout << "Enter a poem of your own creation, one line at a time.\n";
    cout << "Type 'quit' to exit the program.\n\n";

    cout << "Type your poem, pressing the enter key to create a new line.\n\n";
    cin >> user_input;

    if (user_input  == "quit")
    {
        cout << "\nGoodbye! Have a great day.\n";
    }
    else
    {
        getline(cin, user_input);
    }

}

int main()
{
    makePoem();
    return 0;
}
 

Apologies if this question is too vague or such. Thanks for the help.

Upvotes: 2

Views: 266

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596287

You need to read the user's input in a loop, appending each line to your target string, eg:

/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/

#include <string>
#include <iostream>
using namespace std;

void makePoem()
{
    string poem;
    string user_input;

    cout << "Enter a poem of your own creation, one line at a time.\n";
    cout << "Type 'quit' to exit the program.\n\n";

    cout << "Type your poem, pressing the enter key to create a new line.\n\n";

    while (getline(cin, user_input))
    {
        if (user_input == "quit")
            break;

        poem += user_input;
        poem += '\n';
    }

    cout << "\nGoodbye! Have a great day.\n";
}

int main()
{
    makePoem();
    return 0;
}

Upvotes: 1

Antoine Gagnon
Antoine Gagnon

Reputation: 100

This looks like a homework problem so I wont give you actual code but here are some clues :

  • You need a loop that keeps going until the user enters "quit"
  • You then simply add the user input to the user_input string using the += operator
  • To add a newline to a string you add "\n" ex : user_input += "\n";

Upvotes: 0

Related Questions