简体   繁体   English

在 C++ 中读取 C 样式字符串时出现错误

[英]When reading a C-style string in c++ an error appears

Firstly, look at the following simple code.首先看下面的简单代码。

int main(){
    char *name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Your name is: " << name;

    return 0;
}

The previous code gives me the following error warning: deprecated conversion from string constant to 'char*' .前面的代码给了我以下错误warning: deprecated conversion from string constant to 'char*'
but I have been solved the problem by:但我已经通过以下方式解决了这个问题:

const char *name;

After compile the code, I have another error no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'const char*') .编译代码后,我有另一个错误no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'const char*')

What the reason of the previous error, and how to solve it ?上一个错误的原因是什么,如何解决?

You haven't initialized any memory into which the string can be read.您尚未初始化任何可以读取字符串的内存。 char * is a pointer to a location in memory where a string can be read, but the memory first has to be allocated using new or malloc . char *是指向内存中可以读取字符串的位置的指针,但首先必须使用newmalloc分配malloc

However, in C++ there is another, better option: use std::string :但是,在 C++ 中还有另一个更好的选择:使用std::string

#include <string>

int main()
{
    std::string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Your name is: " << name;

    return 0;
}

If you are set on using a c-string, you could do allocate memory and do something like the following:如果您设置为使用 c 字符串,则可以分配内存并执行以下操作:

int main()
{
    char name[MAX_SIZE];
    cout << "Enter your name: ";
    cin.get(name, MAX_SIZE);
    cout << "Your name is: " << name;

    return 0;
}

(Thanks to Neil Kirk for the improvements) (感谢 Neil Kirk 的改进)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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