Problem with creating object for class using input from cin

Hey,

in all simplicity I have variable "char* nameof;" and I store input from "cin" in that variable and try to make object of class by using this stored string.

1
2
3
4
5
6
7
#include "header.h"

char* nameof;
cin >> nameof;

testclass nameof;


ERRORS:

error: conflicting declaration 'test nameof'|
error: 'nameof' has a previous declaration as 'char* nameof'|

There are two problems here. Firstly, you're trying to store input into a memory address that you never set. What's the value of the char pointer nameof? It could be pointing anywhere in the memory, because you never gave it a value, so you're going to store your input into some random memory somewhere. If you're lucky, the OS will spot it and crash your program with a segFault, If you're unlucky, you will trash your own data and you won't even know. This implies that you don't really know what a pointer is and how to use one. Please read this:
http://www.cplusplus.com/articles/EN3hAqkS/
and this:
http://www.cplusplus.com/articles/z186b7Xj/

The second problem is that you created a pointer named nameof, and then you tried to create an object of type testclass, also named nameof. If you have two variables with the same name, how would the compiler know which one you meant? You cannot have two variables with the same name.
Last edited on
umm. Im just a beginner, and still learning about C++, but when you wrote

cin >> nameof ;

nameof with out (*) is the address of the value.

Maybe you should try

cin >> * nameof ;

im still learning about C++ so please tell me if you managed to make it work, so that i can learn too . Thanks

The >> operator is overloaded for char*, so that using it to input to a char* actually causes it to input to whatever that pointer is pointing at.

im still learning about C++ so please tell me if you managed to make it work, so that i can learn too .


Here's how to do it in C++. In C++, we have proper string objects.

1
2
string input;
cin >> input;
Last edited on
Topic archived. No new replies allowed.