C++ 如何在不同的函数中使用和生成全局变量?
我知道我需要尽可能避免全局变量,但不知何故,我需要在其他函数中使用某些变量。 这个程序是一个配方程序。添加、删除和查看配方。一切正常。也许不是最好的代码,但它是有效的。任务的第二部分是确保: 用户输入他需要为食谱服务的人数。程序必须更改配方数量以满足其需要 我的计划是制造一个叫做“乘数”的变量,它乘以每个数量,但我不知道是否有更好的方法。不幸的是,由于我需要的变量在“addRecipe”中,我不可能访问它们。我需要“int-people”和“int-quan[]”,这样我就可以将他想要的份数除以配方中的人数。这将给我一个乘法器,然后我用它乘以数组中的每个数值。然后在不更改配方的情况下以不同方式输出阵列。 这可能不是最好的计划,我已经使用参数尝试过好几次,但我似乎无法让它工作。代码如下,我的尝试也是如此C++ 如何在不同的函数中使用和生成全局变量?,c++,variables,compiler-errors,global,undeclared-identifier,C++,Variables,Compiler Errors,Global,Undeclared Identifier,我知道我需要尽可能避免全局变量,但不知何故,我需要在其他函数中使用某些变量。 这个程序是一个配方程序。添加、删除和查看配方。一切正常。也许不是最好的代码,但它是有效的。任务的第二部分是确保: 用户输入他需要为食谱服务的人数。程序必须更改配方数量以满足其需要 我的计划是制造一个叫做“乘数”的变量,它乘以每个数量,但我不知道是否有更好的方法。不幸的是,由于我需要的变量在“addRecipe”中,我不可能访问它们。我需要“int-people”和“int-quan[]”,这样我就可以将他想要的份数除以
// Recipe.cpp : Defines the entry point for the console application.
//
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
// Practice.cpp : Defines the entry point for the console application.
//
// 2a
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
void deleteRecipe(){
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
cout<< "Please input the file you would like to delete from the list above: "<<endl;
string dName;
cin>>dName;
remove(dName.c_str());
cout<<"The recipe has BEEN DELETED! " <<endl;
system("pause");
}
int addRecipe(){
//PART B OF PROBLEM!
int count = 1;
string title;
string item;
int quan [100];
string units;
int people;
cout<<"What is the title of your new recipe?"<<endl;
cin.ignore();
getline(cin, title);
ofstream outFile(title+".txt", ios::out);
cout<< "How many people will this recipe serve?"<<endl;
cin>>people;
cout<< title << " - Servings: " << people << " people" <<endl;
cout<<" Please type your ingredients in the format as follows. Be to sure to input a '#'upon completion."<<endl;
while (count<1000){
cout<< "Enter Item: "<<endl;
cin.ignore();
getline(cin, item,'#');
cout<< "Enter Quantity: "<<endl;
cin>>quan[];
cout<< ("Enter units")<<endl;
getline(cin, units);
count = count++;
}
cout<< "Thank you for inputting your recipe. To view your recipe, please do nothing."<<endl;
outFile << title <<endl;
outFile<< people << " People" <<endl;
outFile<< item<<endl;
return 0;
}
int viewRecipe(){
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
cout<<"Please type in the name file you want to view from the list above: "<<endl;
string fileName;
string line;
cin>> fileName;
ifstream inData;
inData.open(fileName.c_str());
if (inData.is_open())
{
while ( getline (inData,line) )
{
cout << line << '\n';
}
inData.close();
int multiplier = 0;
char choice;
int newAmount;
cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl;
// PART A OF PROBLEM!
if (choice= '#'){
cout<<"How many servings would you like to adapt the recipe to?"<<endl;
cin>>newAmount;
multiplier = newAmount/ addRecipe(0, );
}
}
return 0;
}
int menu(){
int input = 0;
cout<< "1: View Recipe" <<endl;
cout<< "2: Add Recipe" <<endl;
cout<< "3: Delete Recipe" <<endl;
cout<< "Please select an option"<<endl;
cin>>input;
if (input == 1){
viewRecipe();}
if (input == 2){
addRecipe();}
if (input == 3){
deleteRecipe();}
return 0;
}
int main(){
menu();
system("pause");
cin.get();
return 0;
}
//Recipe.cpp:定义控制台应用程序的入口点。
//
int _tmain(int argc,_TCHAR*argv[]
{
返回0;
}
//Practice.cpp:定义控制台应用程序的入口点。
//
//2a
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
void deleteRecipe(){
DIR*dp;
结构方向*ep;
dp=opendir(“C:\\Users\\The\\Documents\\visualstudio 2010\\Projects\\Recipe\\Recipe”);
如果(dp!=NULL)
{
while(ep=readdir(dp))
放置(ep->d_名称);
(无效)closedir(dp);
}
其他的
perror(“无法打开目录”);
cout我可以想出以下方法来创建和操作全局变量
int& multiplier()
{
static m = 1;
return m;
}
// Later on....
// Set its value. This is an unusual syntax. But it works.
multiplier() = 10;
// Use it.
int foo = multiplier()*bar;
只需在文件顶部定义一个变量并使用它
int multiplier = 1; // Initialize it to a sane value.
// Later on....
// Set its value
multiplier = 10;
// Use it.
int foo = multiplier*bar;
定义一个函数,该函数返回对函数作用域静态变量的引用
int& multiplier()
{
static m = 1;
return m;
}
// Later on....
// Set its value. This is an unusual syntax. But it works.
multiplier() = 10;
// Use it.
int foo = multiplier()*bar;
这里有一个想法(因为,正如你所说,除非绝对必要,否则你不应该使用globals,在你的情况下,这是不必要的):
1.创建一个类成分
:
class ingredient {
public:
string name;
string unit;
double quantity;
ingredient(string n, string u, double q) :
name(n), unit(u), quantity(q) { }
}
2.创建一个类配方
:
class recipe {
vector<ingredient> the_recipe;
public:
recipe() : the_recipe() {}
void addIngredient(const ingredient& i) {
the_recipe.push_back(i);
}
void printProportions(const int servings) {
printf("For %d servings, you need", servings);
for(int i = 0; i < the_recipe.size(); ++i) {
printf("%f %s of %s\n", the_recipe[i].quantity * servings, the_recipe[i].unit, the_recipe[i].name);
}
}
};
搜索“未声明的标识符”-错误消息(应逐字包含)和导致错误消息的行是整个帖子中唯一相关的信息。您是否考虑过创建一个类配方
?然后创建一个方法viewServings(int乘数)
它以人数作为参数,并返回乘以的比例?纳赛尔,我从来没有想过。我是一个初学者,但非常感谢!:)我希望它能起作用:谢谢你的帮助,纳赛尔。你能详细说明这一点,并帮我在代码中实现它吗?我读了struct和vector,但似乎还是不理解还有代码。我知道它的作用,但由于某种原因,我不能在我的任何函数中使用它。我应该把代码放在哪里?谢谢你,纳赛尔!我已经找到了返回值的方法。另一部分是尝试创建一个包含用户输入元素的数组。这些元素然后乘以程序选择的一个数字。然后就是out点击。如果你能帮助我,我将非常感激!:)我已经编辑了答案以满足你的需要,如果你还有任何问题,请告诉我谢谢!现在很容易理解。不过我有一个不同的问题。我需要创建一个循环[10]这需要一个项目、一个数量和单位。问题是我需要将项目、数量和单位存储在十个不同的变量中,然后输出到屏幕上。你知道我该怎么做吗?
int main() {
// create the ingredient objects
ingredient macaroni("macaroni", "grams", 50), cheese("cheese", "grams", 20);
// create a plain recipe
recipe mac_n_cheese;
// add the ingredients
mac_n_cheese.addIngredient(macaroni);
mac_n_cheese.addIngredient(cheese);
// then finally print the proportions using printProportions
mac_n_cheese.printProportions(2); // for 2 people
return 0;
}