[英]How to scan for user input of both strings and ints to put into a 2D array in c
我正在用 C 在二維數組上編寫一個程序,我將根據商店中的員工和產品數量來獲取用戶生成的二維數組。 我無法弄清楚如何將包含名稱和數字的用戶輸入輸入到數組中。
for (int r = 0; r < employees; r++)
{
for (int c = 0;c < numProducts; c++)
{
arr[r][c] = getUserInput();
}
}
因此,您可以使用可以包含string
s 和int
s 的成對向量。
此示例程序允許您逐個節點輸入對,並將其存儲在對( string
和int
)的向量中:
#include <iostream>
#include <vector>
int main()
{
int num;
std::string str;
std::vector<std::pair<std::string, int>> nodes; //container
std::cout << "Enter string and number" << std::endl;
while(std::cin >> str)
{
if(str == "exit") //type exit to leave the input cycle
break;
std::cin >> num;
nodes.push_back(std::make_pair(str, num));
}
for (const auto& p : nodes) // print the products
{
std::cout << p.first << " " << p.second << std::endl;
}
}
您現在可以將它合並到您需要做的事情中,因為您對問題的描述不允許我確切了解您如何將員工與產品和名稱聯系起來。
編輯
因此,根據您的評論,我添加了一個維護std::pair
的新解決方案,它非常易於使用,而且我相信沒有人會抱怨它,因此您需要一個包含對(名稱、值向量)的容器。
我將姓名和值的輸入分開,因為您有一個有多個姓名的員工,因此很難管理輸入。
沒有多少員工和產品,您可以根據需要放置盡可能多的產品價值。
#include <iostream>
#include <vector>
#include <sstream>
int main() {
double temp_num;
std::string str, name;
std::vector<std::pair<std::string, std::vector<double>>> nodes; //container
std::vector<double> values;
while(true){
std::cout << "Enter employee name ('exit' to leave): ";
getline(std::cin, str); //employee name
if (str == "exit") {
break;
}
name = str;
std::cout << "Enter values: ";
getline(std::cin, str); //values
std::stringstream ss(str);
while(ss >> temp_num)
values.push_back(temp_num);
nodes.push_back(std::make_pair(name, values));
}
std::cout << std::endl;
for (const auto& p : nodes) // print names and the products
{
std::cout <<"Name - " << p.first << ": ";
for (const auto& vals : p.second) {
std::cout <<"$"<< vals << " ";
}
std::cout << std::endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.