输入中的字符串数未知(以字母表示)
Unknown number of strings (in letters) in the input
我想写一个程序,在该程序中,n
不同化学元素的名称在输入中的同一行读取(其中1 ≤ n ≤ 17
和n
也在输入中读取((名称用空格隔开(。化学元素的名称应存储在不同的字符串中,以供进一步使用。
由于n
是未知的,我不知道如何制作类似"字符串数组"的东西。当然,我不应该制作17个不同的字符串st1,st2,st3,...
:D。
你能帮帮我吗?任何帮助都将不胜感激,他们会帮我很多忙。
提前谢谢。
听起来你想在一行中阅读并用空格分隔。试试这样的东西:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main()
{
std::string input;
std::getline(std::cin, input); // takes one line, stops when enter is pressed
std::stringstream ss(input); // makes a stream using the string
std::vector<std::string> strings;
while (ss >> input) { // while there's data left in the stream, store it in a new string and add it to the vector of strings
strings.push_back(input);
}
for (std::string s : strings) {
std::cout << "string: " << s << std::endl;
}
}
您提供输入,如H He Li
,通过点击回车终止,字符串存储在strings
中(打印在最后一个循环中用于演示(。
编辑:
我现在看到您也想读取输入中的数字n
。在这种情况下,您不需要stringstream
解决方案。你可以这样做:
int main()
{
int amount;
std::cin >> amount; // read in the amount
std::vector<std::string> strings;
for (int i = 0; i < amount; i++) {
std::string s;
std::cin >> s; // read in the nth string
strings.push_back(s); // add it to the vector
}
for (std::string s : strings) {
std::cout << "string: " << s << std::endl;
}
}
并传递3 H He Li
等输入。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 继承期间显示未知行为的子类
- 如何将ampl中的集合表示为c++中的向量
- std::is_base_of表示ctor编译错误
- 输入中的字符串数未知(以字母表示)
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 具有未知值时的时间复杂性
- c++模板来表示多项式
- 询问在设计我的手臂模拟器功能表示格式1
- CMakeLists.txt中的命名空间表示法
- 链表中写入访问冲突的未知原因
- 正在生成未知类实例
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 读取文件时运行时的未知行为
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 如何计算Big-O表示法中的平均渐近运行时间
- 我应该如何表示我拥有的连续元素序列?
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 重载运算符>>() 表示未知的输入长度/结构