gpt4 book ai didi

c++ - 输入中未知数量的字符串(字母)

转载 作者:太空狗 更新时间:2023-10-29 22:55:08 27 4
gpt4 key购买 nike

我想编写一个程序,在输入的同一行中读取 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之类的输入。

关于c++ - 输入中未知数量的字符串(字母),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53119564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com