繁体   English   中英

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

[英]C++ Array pointer-to-object error

我有一个似乎是一个常见的问题,但是通过对类似问题的回复,我找不到我的问题的解决方案,因为我已经完成了他们的建议,例如使变量成为一个数组。 我有以下代码:

#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;” line并且我不确定为什么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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM