0

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

2 回答 2

2

这条线...

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 )

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

在您的原始函数中,函数参数通过value传递,这意味着调用上下文中的变量被复制,并且该函数只能在这些副本上工作 - 当函数返回时,对副本的任何修改都会丢失。


另外,!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);
}
于 2014-03-30T04:23:28.673 回答
1

您的每个参数都是按值传递的。这意味着当您调用该函数时,您传入的对象将被复制。因此,当它们在函数内部发生更改时,更改将在副本上执行,而不是在您传入的原始文件上执行。要解决此问题,请通过引用传递:

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

& 在对象类型表示我们要将内存地址复制到函数而不是对象之后。因此,当我们对函数内部的对象进行更改时,我们正在更改我们传入的地址处的内存。原始的被更改了。

于 2014-03-30T04:23:45.957 回答