簡體   English   中英

輸入中的字符串數量未知(以字母為單位)

[英]Unknown number of strings (in letters) in the input

我想編寫一個程序,其中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等輸入,通過按Enter鍵終止,並將字符串存儲在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等輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM