簡體   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