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

标签 c++ function return void multiple-value

谁能告诉我为什么对以下变量所做的更改没有被拉到 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/

相关文章:

c - 递归二进制搜索函数缺少什么? (C)

c++ - 'return' 之前的预期主表达式

java - 返回实现接口(interface)的 java 类的类型

c++ - 我应该怎么做才能访问对象的成员变量?

c++ - 浅拷贝或深拷贝或数组

C++使用派生类的对象访问基类的 protected 成员函数

c - 我的 vector 大小加倍的函数似乎不起作用

linux - 为什么我在 `ret' 时会出现段错误? (FASM)

java - 比较 excel 中的列

c++ - 在 Ubuntu 14.04 上从源代码编译时如何链接到 opencv 3.0?