【发布时间】:2015-02-13 02:43:35
【问题描述】:
我正在处理程序中的一个函数以读取用户的输入,然后该函数将检查该函数是否存在然后运行它,但它非常有问题,并且这些函数意味着运行,运行两次。
//functions with a int and a string
std::map<std::string, std::function<void(int, string)>> functionsIS = {
{"printWordWithNumber", numberPlusWord},
};
//functions with no parameters
std::map<std::string, std::function<void()>> functionsNI = {
{"Help", userHelp},
};
void CommandCheck(std::string command){
int paramInt;
string paramString;
for (int i = 0; i < functionsIS.size(); i = i++){
if (functionsIS[command]){
std::cout << "Accessed '" << command << "' reading requirements..." << std::endl;
std::cout << "Enter paramater one (integer) : ";
std::cin >> paramInt;
std::cout << std::endl<<"Enter paramater two (string)" << std::endl;
std::cin.ignore();
std::getline(std::cin,paramString);
std::cout << "running..." << std::endl;
functionsIS[command](paramInt,paramString);
}
}
for (int i = 0; i < functionsNI.size(); i = i++){
if (functionsNI[command]){
std::cout << "Accessed '" << command << "' running..." << std::endl;
functionsNI[command]();
}
}
}
这是你可以运行的版本:
来源:
#include <iostream>
#include <map>
#include <windows.h>
#include <string>
#include <vector>
#include <map>
#include <functional>
#include "userFunctions.h"//header file for functions
using namespace std;
std::string input;
//functions with a int and a string
std::map<std::string, std::function<void(int, string)>> functionsIS = {
{ "printWordWithNumber", numberPlusWord },
};
//functions with no parameters
std::map<std::string, std::function<void()>> functionsNI = {
{ "Help", userHelp },
};
void CommandCheck(std::string command){
int paramInt;
string paramString;
for (int i = 0; i < functionsIS.size(); i = i++){
if (functionsIS[command]){
std::cout << "Accessed '" << command << "' reading requirements..." << std::endl;
std::cout << "Enter paramater one (integer) : ";
std::cin >> paramInt;
std::cout << std::endl << "Enter paramater two (string)" << std::endl;
std::cin.ignore();
std::getline(std::cin, paramString);
std::cout << "running..." << std::endl;
functionsIS[command](paramInt, paramString);
}
}
for (int i = 0; i < functionsNI.size(); i = i++){
if (functionsNI[command]){
std::cout << "Accessed '" << command << "' running..." << std::endl;
functionsNI[command]();
}
}
}
int main(){
do{
std::cout << "Waiting For Command..." << std::endl;
cin >> input;
CommandCheck(input);
} while (input != "end");
return 0;
}
创建一个名为“functions”的头文件并粘贴:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void numberPlusWord(int number, std::string word){
std::cout << word << std::endl;
std::cout << number << std::endl;
}
void userHelp(){
std::cout << "I can help!" << std::endl;
}
【问题讨论】:
-
您的代码不完整。请编辑您的帖子并添加MVCE。
-
永远不要
i = i++。必须是i++。