我正在读取目录中的文件并将其传递给函数,我认为我做错了一种方式,无法弄清楚。
这是我的代码,它首先读取文件夹中的文件,然后将其发送给函数以进行进一步的操作。
#include <dirent.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
std::vector<std::string> fileName;
int main(void)
{
DIR *d;
struct dirent *dir;
vector<string> fileList;
int i=0;
d = opendir("files");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
i++;
fileList.push_back(dir->d_name);
}
for(int i=0;i<fileList.size();i++) {
cout<<fileList[i]<<endl;
doSomething(fileList[i]);
}
closedir(d);
}
return(0);
}
int doSomething(fileName) {
//do something
}
错误
main.cpp: In function ‘int main()’:
main.cpp:29:28: error: ‘doSomething’ was not declared in this scope
doSomething(fileList[i]);
^
main.cpp: At global scope:
main.cpp:37:26: error: cannot convert ‘std::vector<std::basic_string<char> >’ to ‘int’ in initialization
int doSomething(fileName) {
^
main.cpp:37:28: error: expected ‘,’ or ‘;’ before ‘{’ token
int doSomething(fileName) {
^
由于您的doSomething
函数是在main之后定义的,因此它不可见,从而导致第一个错误。正确的方法是至少首先声明该函数:
int doSomething(); //declaration
int main()
{
doSomething(); //now the function is declared
}
//definition
int doSomething()
{
}
现在,发出第二个和第三个错误,因为您没有fileName
在函数定义中包括参数的类型。根据您的代码,它应该是一个字符串:
int doSomething(string fileName)
{
}
我还注意到,尽管此函数返回int
,但您并未使用它的返回值。但是,请不要忘记从中获取return
某些东西doSomething
,否则将导致未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句