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;"中。线路和不确定为什么作为resarr是一个int数组,我试图从另一个int变量分配一个值。我是C 的新手,所以任何帮助都会很棒,因为我真的很困惑!
谢谢!
问题是,您已声明自己的功能来引用单个string
和int
,而不是数组。应该是:
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;
}
相关文章:
- 对象错误地显示为引用?
- 调用带有指针对象错误的指针变量
- 为什么谷歌测试/模拟显示 std::unique_ptr 泄露的模拟对象错误?
- C 数组指向对象错误
- C++:对象错误的多重定义
- 子数组分配:使用聚合对象错误的预期"{...}"进行初始化
- C 字符串对象错误字符
- 声明 Windows API 结构 (DCB) 的对象 - 错误 C4430:缺少类型说明符 - 假定为 int
- 无法调用成员函数而不出现对象错误
- C++指针/对象错误
- C++排序矢量对象错误
- C++:在映射中存储类对象(错误:获取类型为"Node"的临时对象的地址)
- 使用三元运算符初始化类对象错误
- 帧缓冲区对象错误
- 实例化新对象 - 错误
- C++打印出对象错误
- 如何更正类型对象错误
- 简单指针对象错误C++
- 运算符重载添加两个对象错误
- c++列表对象错误