C 数组指向对象错误

C++ Array pointer-to-object error

本文关键字:对象 错误 数组      更新时间:2023-10-16

我有一个似乎是一个普遍的问题建议将变量变为数组。我有以下代码:

#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <future>
using namespace std;
string eng2Str[4] = { "money", "politics", "RT", "#"};
int resArr[4];
int main()
{
    engine2(eng2Str[4], resArr[4]);
    system("Pause");
    system("cls");
    return 0;
}
void engine2(string &eng2Str, int &resArr)
{
    ifstream fin;
    fin.open("sampleTweets.csv");
    int fcount = 0;
    string line;
    for (int i = 0; i < 4; i++) {
        while (getline(fin, line)) {
            if (line.find(eng2Str[i]) != string::npos) {
                ++fcount;
            }
        }
        resArr[i] = fcount;
    }
    fin.close();
    return;
}

在您标记为重复之前,我已经确定以下几点:

  • 我要分配的数组和变量都是int
  • 它的数组

错误是:

表达式必须具有指针到对象类型

错误发生在" resarr [i] = fcount;"中。线路和不确定为什么作为resarr是一个int数组,我试图从另一个int变量分配一个值。我是C 的新手,所以任何帮助都会很棒,因为我真的很困惑!

谢谢!

问题是,您已声明自己的功能来引用单个stringint,而不是数组。应该是:

void engine2(string *eng2Str, int *resArr)

或:

void engine2(string eng2Str[], int resArr[])

然后,当您调用它时,您可以将数组名称作为参数提供:

engine2(eng2Str, resArr);

另一个问题是该功能中的while循环。这将在for()循环的第一次迭代期间读取整个文件。其他迭代将无需阅读任何内容,因为它已经在文件的末尾了。您可以回到文件的开始,但是更好的方法是重新排列两个循环,因此您只需要读取一次文件即可。

while (getline(fin, line)) {
    for (int i = 0; i < 4; i++) {
        if (line.find(eng2Str[i]) != string::npos) {
            resArr[i]++;
        }
    }
}

我建议使用std :: vector而不是纯C数组。在您的代码中,还有更多问题。您将两个数组的第四个元素传递给了Engine2函数。根据您对void engine2(string &eng2Str, int &resArr)的定义,您期望引用字符串(不是数组/向量(和INT的地址/引用 - 您需要将指针传递给Resarr的第一个元素。

#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <future>
using namespace std;
vector<string> eng2Str = { "money", "politics", "RT", "#" };
int resArr[4] = {};
void engine2(const vector<string>& eng2Str, int* resArr)
{
    ifstream fin;
    fin.open("sampleTweets.csv");
    int fcount = 0;
    string line;
    for (int i = 0; i < 4; i++) 
    {
        while (getline(fin, line)) 
        {
            if (line.find(eng2Str[i]) != string::npos)
            {
                ++fcount;
            }
        }
        resArr[i] = fcount;
    }
    fin.close();
    return;
}
int main()
{
    engine2(eng2Str, resArr);
    system("Pause");
    system("cls");
    return 0;
}