从 void 函数访问局部变量

Accessing local variables from void functions

本文关键字:局部变量 访问 函数 void      更新时间:2023-10-16

我有两个函数,分别读取文件和初始化包含从读取的文件解析的数据的变量。

这些变量包括几个向量、计数器(行数)和一些奇异变量(字符串和整数)。

我遇到的问题是这些变量都需要在后面的函数中访问,这个想法是避免全局变量。由于函数是空的,它们不能返回变量,我发现(与我的普通 Python 语言不同)返回多个变量很困难。

有什么更好的方法呢?

每个 read*() 函数中的向量都需要在我正在构建的新函数中访问。但我还需要 num* 变量,以及食谱和上菜变量。

编辑:我的代码当前

#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
void readNutrients(string input_file) {
ifstream in(input_file.c_str());
string line;
vector<string> nName, nUnits;
vector<double> nAmount, nCalories;
string name, units;
double amount, calories;
int numNut = 0;
while (getline(in, line)) {
numNut++;
int pos = line.find(';');
name = line.substr(0, pos);
nName.push_back(name);
line = line.substr(pos + 1);
istringstream iss(line);
iss >> amount >> units >> calories;
nAmount.push_back(amount);
nUnits.push_back(units);
nCalories.push_back(calories);
}
}
void readRecipe(string input_file) {
ifstream in(input_file.c_str());
string line;
string recipe;
vector<string> rName, rUnits;
vector<double> rAmount;
string name, units;
double amount;
double servings;
int numIng = 0;
while (getline(in, line)) {
numIng++;
if (numIng == 1) {
int pos = line.find('n');
recipe = line.substr(0, pos);
}
else if (numIng == 2) {
istringstream iss(line);
iss >> servings;
}
else {
istringstream iss(line);
iss >> amount >> units >> ws;
rAmount.push_back(amount);
rUnits.push_back(units);
getline(iss, name);
rName.push_back(name);
}
}
}
void readFiles(string nutrientFile, string recipeFile) {
readNutrients(nutrientFile);
readRecipe(recipeFile);
}

int main(int argc, char** argv) {
readFiles(argv[1], argv[2]);
return 0;
}

由于您包含了代码,因此我对正在发生的事情有了更好的了解。

您需要创建一个可以保存解析结果的结构。由于您的函数没有返回任何内容,因此您无法访问它的结果是合乎逻辑的。

我认为您在这里的目的是从文件中读取营养列表,并从该文件中读取每个营养物质并填写程序中的列表。

问题是你的程序不知道是什么使营养素成为营养素。你应该教他,通过宣布什么使营养素成为营养素:

struct Nutrient {
std::string name, unit;
double amount, calories;
};

然后,与其创建一堆值列表,不如创建一个营养素列表。

std::vector<Nutrient> readNutrients(std::string input_file) {
// Here declare your vector:
std::vector<Nutrient> nutrients;
// declare line, calories, name...
while (std::getline(in, line)) {
// fill your variables name calories etc...
// create a nutrient
Nutrient n;
// fill the nutrient with values from the parsing.
n.name = name;
n.unit = units;
n.amount = amount;
n.calories = calories;
// add the nutrient to the list.
nutrients.push_back(n);
}
// return a filled list of nutrient.
return nutrients;
}

顺便说一下,您不需要 num* 变量,因为nutrients.size()会返回列表中的营养素数量。

该解决方案与配方相同:创建一个类型以在程序中添加配方的概念,并使用该类型。

请注意,此代码不是最佳的,std::move从 C++11 开始应该会给你带来巨大的速度。

我不清楚你的情况。但是由于您无法将结果作为 void 函数的返回值获取,因此它可能会通过使用指针或引用类型的输出参数来获取结果。

例如:

void _read(const char* file,  vector<string>& r_list, int* pState)
{
// do parsing file
// do outputs
*pState = (your_number);
r_list.push_back("your string");
} 

希望这对你有用。