如何使用cin指定char指针?

时间:2013-05-02 01:41:22

标签: c++

所以基本上当我尝试这样做时

char* inputFileName;
cout<<  "Filename: "; cin>>*inputFileName;

它允许我输入文件名但是当我按下回车时我得到一个未处理的异常错误。有任何想法吗?

如果我尝试

,也可以编辑
char* inputFileName;
cout<<  "Filename: "; cin>>inputFileName;

当我尝试运行它时,调试断言失败。

2 个答案:

答案 0 :(得分:9)

您需要传入指针,而不是解除引用的指针,并为char *分配内存

#include <iomanip>
#include <iostream>
using namespace std;

int main(){
    const size_t BUFFER_SIZE = 1024;
    char inputFileName[BUFFER_SIZE];
    cout << "Filename: ";
    cin >> setw(BUFFER_SIZE) >> inputFileName;
    cout << inputFileName << endl;
}

char inputFileName[BUFFER_SIZE];之外的另一个选项是

char *inputFileName = new char[BUFFER_SIZE];

以后

delete [] inputFileName;

答案 1 :(得分:4)

尝试使用:

#include <iostream>
using namespace std;

int main()
{
    char *inputFileName = new char[50];
    cout << "Filename: ";
    cin >> inputFileName;
    cout << inputFileName << endl;
    /* .... */
    delete [] inputFileName;
}