gpt4 book ai didi

c++ - 如何将许多值从 void 返回到 main (c++)

转载 作者:行者123 更新时间:2023-11-28 00:31:30 25 4
gpt4 key购买 nike

谁能告诉我为什么对以下变量所做的更改没有被拉到 main 中?

我对此很陌生,所以请保持简单。

如果您需要我的更多代码,请告诉我:D

void BannedWordsArrayCreate (string filePathInBanned, vector<string> bannedWords, vector<int> bannedWordsCount, vector<int> containsBannedWordsCount ) {

cout << "Please enter the file path for the banned word list. (no extension.): " << endl; //User enters file name
cout << "E.g. C:\\Users\\John\\banned" << endl;
cin >> filePathInBanned;
filePathInBanned += ".txt"; //Takes User defined file name and adds .txt

ifstream inFile;
inFile.open(filePathInBanned,ios::in); //opens file

if (!inFile) //if file cannot be opened: exits function.
{
cerr << "Can't open input file." << filePathInBanned << endl;
exit(1);
}

else if (inFile.is_open()) //if file opens: puts file into vector.
{
string bw = "nothing"; //temporary string used to signal end of file.
while(!inFile.eof() && bw != "")
{
inFile >> bw;
if (bw != "")
{
bannedWords.push_back(bw);
}
}
}
inFile.close();
cout << endl << "Done!" << endl << endl;

for(int i = 0; i < bannedWords.size(); i++)
{
bannedWordsCount.push_back(0);
containsBannedWordsCount.push_back(0);
}
}

最佳答案

这一行...

void BannedWordsArrayCreate (string filePathInBanned,
vector<string> bannedWords, vector<int> bannedWordsCount,
vector<int> containsBannedWordsCount )

...需要通过引用请求变量(使用& 标记)...

void BannedWordsArrayCreate (string& filePathInBanned,
vector<string>& bannedWords, vector<int>& bannedWordsCount,
vector<int>& containsBannedWordsCount )

引用基本上是原始变量(由调用者提供)的别名或替代名称,因此“对引用”所做的更改实际上是在修改原始变量。

在您的原始函数中,函数参数是按值传递的,这意味着调用上下文中的变量被复制,并且函数只对那些变量起作用拷贝 - 当函数返回时,对拷贝的任何修改都将丢失。


另外,!inFile.eof() 没有被正确使用。关于这个问题有很多 Stack Overflow Q/A,但总的来说,eof() 标志只能在流知道您要转换的内容后设置(例如,如果你尝试读入一个字符串,它只能找到很多空格,然后它会失败并设置 eof,但是如果你向流询问下一个字符是什么(包括空格)那么它会成功返回该字符而无需点击/设置eof)。您可以将输入处理简化为:

if (!(std::cin >> filePathInBanned))
{
std::cerr << "you didn't provide a path, goodbye" << std::endl;
exit(1);
}

filePathInBanned += ".txt"; //Takes User defined file name and adds .txt

if (ifstream inFile(filePathInBanned))
{
string bw;
while (inFile >> bw)
bannedWords.push_back(bw);
// ifstream automatically closed at end of {} scope
}
else
{
std::cerr << "Can't open input file." << filePathInBanned << std::endl;
exit(1);
}

关于c++ - 如何将许多值从 void 返回到 main (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22740181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com