C++未知长度字符串的数组,其行为类似于 Python 字符串列表
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;
}
相关文章:
- 类似于strcat()的函数出现问题
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 算术运算的结果类似于:C浮点变量中的1/3
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 创建类似于布尔值的变量类型
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- Java 中是否有类似于 C++ 中引用类型"&"的内容?
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- 构造一个类似于JSON文件c++的字符串
- C# 是否有办法将双精度数组强制转换为类似于C++转换为 char* 的字符串?
- shared_ptr的子数据(类似于?的子字符串)
- search用字符串列表输入数字(类似于t9字典)
- 如何传递字符串或类似于结构或对象名称的东西
- 创建行为类似于字符串流的类的最简单方法
- 将字符串的向量连接到std::ostream(类似于boost::Join)
- 在C++中创建原始文本字符串,类似于 C# 的"@ string"
- 为什么std::字符串串联运算符的工作原理类似于右关联运算符
- 如何检查_bstr_t是否包含字符串(类似于str.find)
- 基于特定分隔符拆分字符串的最有效的c++方法是什么?类似于python中的split方法
- 比较两个字符串(类似于GNUdiff的操作)