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

时间:2018-11-02 13:33:48

标签: c++

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

由于n是未知的,因此我不知道如何制作类似“字符串数组”的内容。当然,我不应该制作17个不同的字符串st1,st2,st3,...:D。

能帮我吗?任何帮助将不胜感激,他们将为我提供很多帮助。

谢谢。

1 个答案:

答案 0 :(得分:2)

听起来您想读一行并用空格分隔。尝试这样的事情:

#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之类的输入。