So basically when I try to do this
char* inputFileName;
cout<< "Filename: "; cin>>*inputFileName;
it lets me input the filename but when I press enter I get an unhandled exception error. Any ideas?
edit also if I try
char* inputFileName;
cout<< "Filename: "; cin>>inputFileName;
I get a debug assertion failed when I try to run it.
The cin can also be used with some member functions which are as follows: It reads a stream of characters of length N into the string buffer, It stops when it has read (N – 1) characters or it finds the end of the file or newline character ( ). Below is the C++ program to implement cin.getline ():
Please read our previous articles, where we discussed Pointer to function in C. At the end of this article, you will understand what is Character Pointer and why do we need Character Pointer, and how to create Character Pointers. A pointer may be a special memory location that’s capable of holding the address of another memory cell.
When you set a pointer equal to an array ( char *ptr = array; ) is like making it pointing to the first element of that array: char *ptr = & (array [0]);. Since arrays use contiguous memory, the pointer is like as it is pointing to the array:
A pointer to char always points to a single char. An array is like a pointer but it will always point to its first element: When you set a pointer equal to an array ( char *ptr = array; ) is like making it pointing to the first element of that array: char *ptr = & (array [0]);.
You need to pass in the pointer, not the dereferenced pointer, and have allocated memory for the 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
char *inputFileName = new char[BUFFER_SIZE];
and later
delete [] inputFileName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With