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

标签 c++ pointers file-io 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

这是我的代码:

#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 << " ";               
        }
    }  
}

最佳答案

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

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

fin.open(argv[1]);

如果您有其中之一但需要 C 风格的字符串,您可以在 std::string 对象上调用 c_str()。 (从历史上看,如果您有 std::string,则必须这样做才能调用 fin.open();但是从 C++11 开始,您可以通过直接输入)。

关于c++ - 使用 argv[1] 作为文件名问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063986/

相关文章:

c++ - 为什么 Stroustrup 的书展示了默认的函数模板参数,这在当时是不允许的?

c++ - 为什么我们可以锁定在 const 对象中定义的互斥量?

json - 如何在 Go 中使用自定义属性类型进行 json 解码

c - 这些表达式之间的差异 : int* a = 0; int* a = 10;

c++ - *b= *b+1 和 *b++ 之间的区别

java - 如果与用户输入的字符串不匹配,如何删除文本文件中的字符串?

javascript - 停止打开输入类型文件 'file selection window'

java - 从maven项目中的相对路径读取文件

c++ - 生命游戏 - 算法问题 C++

c++ - 如何使用多线程 C++ 在循环中启动多个操作