gpt4 book ai didi

c++ - 如何使用Enter键创建新行,而不是输入字符串?

转载 作者:行者123 更新时间:2023-12-03 07:02:06 24 4
gpt4 key购买 nike

我必须编写一个程序,允许用户输入多行诗,按Enter键在诗中创建新行。这首诗的所有行都需要存储在单个字符串中,而且我不确定如何将“\ n”连接到用户输入。另外,一旦用户读完了这首诗,我就不确定如何继续前进并在程序中执行更多代码。
这是我到目前为止的代码:

/*
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;
}

如果这个问题太含糊或类似,我们深表歉意。谢谢您的帮助。

最佳答案

您需要循环读取用户的输入,并将每行追加到目标string,例如:

/*
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;
}

关于c++ - 如何使用Enter键创建新行,而不是输入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64359713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com