如何使用GLOBAL变量并在不同的函数中使用?

时间:2014-05-13 19:40:42

标签: c++ variables compiler-errors global undeclared-identifier

我知道我需要尽可能地避免全局变量,但不知何故我需要在其他函数中使用某些变量。 这个程序是一个食谱程序。添加,删除和查看配方。一切正常。也许不是最好的代码,但它的工作原理。这项任务的第二部分是为了: 用户输入他需要服务食物的人数。计划必须改变食谱的数量,以满足他的需要。

我的计划是制作一个名为“乘数”的变量,乘以每个数量,但我不知道是否有更好的方法。不幸的是,因为我需要的变量是“addRecipe”,所以我无法访问它们。我需要“int people”和“int quan []”所以我可以将他想要的份数除以配方所用的人数。这将给我一个乘数,然后我用它来乘以数组中的每个NUMERICAL值。然后以不同方式输出阵列而不改变配方。 这可能不是最好的计划,我已经尝试了几次使用参数,但我似乎无法使其工作。代码如下,我的尝试。

// 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;
}

我的尝试不起作用:

int addRecipe(int people, int quan[]){
    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(int multiplier){
     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;
    int x = addRecipe(people, void)
    cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl;
    if (choice= '#'){
        cout<<"How many servings would you like to adapt the recipe to?"<<endl;
        cin>>newAmount;
        multiplier = newAmount/ addRecipe(, );

    }

2 个答案:

答案 0 :(得分:0)

我可以想到以下创建和操作全局变量的方法。

  1. 只需在文件顶部定义一个变量并使用它。

    int multiplier = 1; // Initialize it to a sane value.
    
    // Later on....
    // Set its value
    multiplier = 10;
    
    // Use it.
    int foo = multiplier*bar;
    
  2. 定义一个函数,该函数返回对函数范围的静态变量的引用。

    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;
    

答案 1 :(得分:0)

这是给你的一个想法(因为,正如你所说的,除非绝对必要,否则你不应该使用全局变量,在你的情况下,它不是必需的):

1.创建class ingredient

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

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);
        }  
    }
};

您怎么看?

<强>更新

3.在你的程序中使用它:

以下是一个如何使用它的示例(另请注意我已经修改了上面的struct。为了避免可能的混淆,我将其更改为一个类。它们在C ++中基本相同,有一个小的差异)。无论如何,这是一个例子:

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;
}