![](/img/trans.png)
[英]Python converting a tuple (of strings) of unknown length into a list of strings
[英]C++ array of unknown length strings with behaviour like a Python list of strings
我正在尝试从 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.