C++未知长度字符串的数组,其行为类似于 Python 字符串列表

C++ array of unknown length strings with behaviour like a Python list of strings

本文关键字:字符串 类似于 列表 Python 数组 未知 C++      更新时间:2023-10-16

我正在尝试从Python背景中学习C++。我一直发现很难找到C++具有引人入胜的示例或玩具程序指南的学习材料,这些材料具有对我来说简单但有意义的内容(不要误会我的意思 - 有大量的解释性材料,但我发现我通过玩具示例学习得最好,但仍然有一些实用性(。

因此,作为练习,我想用C++编写一个程序,基本上可以存储一堆逐行输入的句子,然后一次打印出这些句子。如果我只是展示如何在 Python 3 中编写它,解释起来可能会容易一些:

print("Your notes are now being recorded. Type 'e' and press enter to stop taking notes.")
note_list = []
for i in note_list:
a = input()
if a == 'e':
break
note_list.append(a)
for i in note_list:
print(i)

我并不幻想这几乎可以用C++轻松表达,但我在知道如何复制字符串存储组件时遇到了麻烦。

目前,我只能表达我的启动提示并初始化C++字符串值,如下所示:

# include <iostream>
# include <string>
int main()
{
std::cout << "Your notes are now being recorded. Type 'e' and press enter to stop taking notes.n";
std::string x;
int flag = 1;
while (flag == 1)
{
// presumably a function will go here that adds any input unless 
// it's 'e' which will make the flag = 0
std::getline(std::cin, x) // some variation of this maybe?
}
// Once I have my collection of strings (an array of strings?) I assume I 
// use a C++ for loop very similar to how I might use a Python for loop. 
return 0;
}

我能不能对如何实现我的目标有一些指导?即使只是一些特定资源的大致方向也很棒。

同样,我的主要不确定性在于弄清楚如何以类似于我在 Python 中简单地附加列表的方式存储每个字符串(或至少尽可能容易(。

如果问题有点宽泛,我深表歉意。

谢谢。

您在这里寻找的是两种不同的东西:存储输入直到满足条件,然后输出每个存储的输入。

获取输入

为了收集输入,鉴于您不知道预期有多少输入,我会使用一个向量 - 它类似于 python 列表,因为它是一种动态集合类型。您需要包含它:

#include <vector>

有多种方法可以将值放入向量中,但push_back(value)的工作方式类似于 python 的list.append- 它将指定的值添加到集合的末尾。

std::vector<std::string> inputs; // A vector (of strings) to collect inputs
while(true){  // Infinite loop
// Retrieve input
std::string input;
std::getline(std::cin, input);
// Check for terminal input
if(input == "e"){
break;
}
// Add the input to our collected inputs
inputs.push_back(input);
}

输出存储的字符串

要输出存储的输入,您可以使用传统的 for 循环,但来自 python 背景,您可能会发现基于范围的 for 循环(也称为 for-each 循环(感觉更熟悉。

// Range-based for loop
for(const auto& output : inputs){
std::cout >> output >> endl;
}