输入中的字符串数未知(以字母表示)

Unknown number of strings (in letters) in the input

本文关键字:表示 未知 字符串 输入      更新时间:2023-10-16

我想写一个程序,在该程序中,n不同化学元素的名称在输入中的同一行读取(其中1 ≤ n ≤ 17n也在输入中读取((名称用空格隔开(。化学元素的名称应存储在不同的字符串中,以供进一步使用。

由于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等输入。