C++字符串输入

Mar*_*ton 1 c++

我的书说如果我想读一个最大长度为40个字符的字符串,我必须声明一个长度为41的变量,但它没有说明原因.

char name[41];
cin >> name;
cout << name << endl;
Run Code Online (Sandbox Code Playgroud)

我知道这是一个新手问题,我确实是一个C++新手.

我希望你能帮助我.谢谢.

编辑:

感谢您的回答,我没想到在如此短的时间内获得如此多的好消息.

  1. 谁负责在char数组的末尾插入NULL终止符?

  2. 按Enter后"\n"会发生什么?

再次感谢.

Dan*_*vil 6

用a std::string来读cin.那么您不需要事先知道缓冲区需要多大.

std::string input;
cin >> input;
cout << intput;
Run Code Online (Sandbox Code Playgroud)

如果您需要C风格的数组,您可以:

const char* cstyle = input.c_str();
Run Code Online (Sandbox Code Playgroud)

如果使用C样式字符串,则最后一个字符始终为空终止符'\0'以指示字符串的结尾.知道字符序列的结束位置非常重要.

一些例子:

char* text = "hello"; // the compiler puts an extra '\0' at the end
std::string str("hello"); // does not have a null terminator! (before C++11)
str.c_str(); // this returns "hello\0" with a null terminator
Run Code Online (Sandbox Code Playgroud)