使用argv [1]作为文件名问题

Imp*_*lse 1 c++ file-io pointers cstring

我正在尝试读取名为的文件argv[1],但我不知道我是如何做到的.感觉它很简单,编译时我得到的错误信息是,

main.cpp: In function ‘void* ReadFile(char**, int&)’:
main.cpp:43:22: error: request for member ‘c_str’ in ‘*(argv + 8u)’, which is of non-class type ‘char*’
make: *** [main.o] Error 1
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

#include "movies.h"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

void *ReadFile(char*[], int&);
int size;
int main(int argc, char *argv[])
{   
    char * title[100];

    cout << argv[1] << endl;
    //strcpy(argv[1],title[100]);
    //cout << title << endl;
    ReadFile(argv , size);

    return 0;
}

void *ReadFile(char * argv[] , int& size)
{
    char data;
    //char title[50];
    //strcpy(title,argv[1]);
    //cout << title << endl;
    ifstream fin;
    fin.open(argv[1].c_str()); //filename

    if (fin.good())
    {
        fin >> data;       
        cout << data << " ";                      
        while (!fin.eof( ))      
        {
            fin >> data; 
            cout << data << " ";               
        }
    }  
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 5

正如错误所示,您正在尝试c_str()在非类型类型上调用成员函数.argv[1]是指向字符数组(C样式字符串)的指针,而不是类对象.

只需将指针传递给open():

fin.open(argv[1]);
Run Code Online (Sandbox Code Playgroud)

你可以调用c_str()一个std::string对象,如果你有一个但需要一个C风格的字符串.(从历史上看,fin.open()如果你有,你必须这样做才能调用std::string;但是从C++ 11开始,你可以直接传递那种类型).