以编程方式输入新行

Enter a new line programmatically

本文关键字:新行 输入 方式 编程      更新时间:2023-10-16

我有一个带有文本的vector of std::string,其中有几行。字符串(。这些线是矢量的元素。

我选择一个范围的数字,例如:0 and 2,所选范围被删除,我在向量的开头插入一个新字符串,一个字符串(我删除的地方(。

But I would like,当我输入一个字符串并在同一字符串中键入"">时,to see in the outputting result text which will consist of two lines.

为了获取带有spaces的字符串,我使用std::getline()

std::cout << "Enter insreting text: ";
std::getline(std::cin >> std::ws, text);

在控制台模式下:

Enter insreting text: hello n Bye

我的愿望结果应该是

你好

再见

可能是我使用 std::getline() 来获取字符串是不对的。请问有什么提示吗?

正如我的评论中提到的,如果您输入,std::getline()捕获的文本

hello n Bye

"hello \n Bye"

显示为文字。

要输出

hello
 Bye

您需要将"\n"的出现次数替换为 "n"

@Remy已经在他的回答中发布了如何做到这一点的代码。

std::string text;
std::cout << "Enter inserting text: ";
std::getline(std::cin >> std::ws, text);
std::string::size_type pos = text.find("\n");
while (pos != std::string::npos)
{
    text.replace(pos, 2, "n");
    pos = text.find("\n", pos+1);
}
std::cout << text;

现场演示