>*inputFileName; it all...">

How to assign char pointer with cin?

So basically when I try to do this

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

it allows me to enter a file name, but when I press the enter key, I get an unhandled exception error. Any ideas?

edit also if i try

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

I get a debugging error message when I try to start it.

+4
source share
2 answers

You need to pass a pointer, not a dereferenced pointer, and allocated memory for 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; } 

Another option besides char inputFileName[BUFFER_SIZE]; , is an

 char *inputFileName = new char[BUFFER_SIZE]; 

and later

 delete [] inputFileName; 
+8
source

Try using this:

 #include <iostream> using namespace std; int main() { char *inputFileName = new char[50]; cout << "Filename: "; cin >> inputFileName; cout << inputFileName << endl; /* .... */ delete [] inputFileName; } 
+5
source

All Articles