C ++数组指针到对象的错误

时间:2017-05-31 23:30:15

标签: c++

我有一个似乎是一个常见的问题,但是阅读对类似问题的回复我根本无法找到我的问题的解决方案,因为我已经完成了他们所建议的内容,例如制作变量数组。我有以下代码:

#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
  • 它是一个数组

错误是:

  

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

错误发生在&#34; resArr [i] = fcount;&#34; line并且我不确定为什么resArr是一个int数组,我试图从另一个int变量赋值。我对C ++很陌生,所以任何帮助都会很棒,因为我真的被卡住了!

谢谢!

2 个答案:

答案 0 :(得分:2)

问题在于,您已声明自己的函数引用了单个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]++;
        }
    }
}

答案 1 :(得分:1)

我建议使用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;
}