简体   繁体   中英

std::cin limitations can't input LPCSTR

I have a program in which one of the variables types is a LPCSTR and the user needs to input that however std::cin can't give LPCSTR a value here is some code

LPCSTR windowName;
std::cin >> windowName;

The type LPCSTR is just a pointer, it's an alias for const char * .

So you have two problems with the statement

std::cin >> windowName;

The first is that you use an uninitialized pointer as the destination. The second is that the pointer (once properly initialized) points to a constant memory area, that you can't write to or change.

The compiler should complain about the second issue (pointer to constant memory), while an uninitialized pointer will lead to undefined behavior (and possible crashes) at run-time.


The easiest solution is to use a std::string for the string, and when you need an LPCSTR simply use the c_str() member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM