【问题标题】:Using argv[1] as a filename problems [duplicate]使用 argv[1] 作为文件名问题 [重复]
【发布时间】:2014-06-05 23:30:18
【问题描述】:

我正在尝试读取以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()std::string 类的方法。 char 根本没有方法!
  • 完全一样的问题,甚至有文字argv[1].c_str()Why should I use c_str() in functions
  • 不管怎样,为什么size 是一个全局变量,为什么要将所有程序参数传递给ReadFile,而不仅仅是文件名?

标签: c++ pointers file-io cstring


【解决方案1】:

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

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

fin.open(argv[1]);

如果您有其中一个但需要 C 样式的字符串,您可以在 std::string 对象上调用 c_str()。 (从历史上看,如果您有 std::string,则必须这样做才能调用 fin.open();但从 C++11 开始,您可以直接传递该类型)。

【讨论】:

  • 谢谢,效果很好!我是一个矮胖的第一年,对不起,如果我激怒了任何人:P
【解决方案2】:

.c_str() 函数是为string 对象定义的,用于将其转换为char *。您正尝试在 char * 上使用它。而是使用fin.open(argv[1]),因为它已经是一个 C 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多