Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a char pointer with cin?

Tags:

c++

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.

like image 845
Elliot678 Avatar asked May 02 '13 01:05

Elliot678


People also ask

How to use CIN in C++?

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 ():

What is character pointer in C and why do we need it?

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.

How do you set a pointer to an array in C?

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:

What is the difference between a pointer to a char and 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]);.


1 Answers

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;
like image 61
Dr.Tower Avatar answered Sep 22 '22 20:09

Dr.Tower