c++ char 数组,在cin.getline()中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7549280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:06:27  来源:igfitidea点击:

c++ char arrays, use in cin.getline()

c++stringarrays

提问by BrainPermafrost

I have the following code:

我有以下代码:

char myText[256];
cin.getline(myText,256);

Why exactly do I have to pass a character array to cin.getline() and not a string?

为什么我必须将字符数组传递给 cin.getline() 而不是字符串?

I have read that in general it is better to use strings than character arrays. Should I then convert a character array to a string after retrieving input with cin.getline(), if that is possible?

我读过一般来说使用字符串比使用字符数组更好。如果可能的话,我应该在用 检索输入后将字符数组转换为字符串cin.getline()吗?

采纳答案by FailedDev

You are using the member method of istream. In this case cin. This function's details can be found here :

您正在使用 istream 的成员方法。在这种情况下,cin。可以在此处找到此功能的详细信息:

http://en.cppreference.com/w/cpp/io/basic_istream/getline

http://en.cppreference.com/w/cpp/io/basic_istream/getline

However you could use std::getline

但是你可以使用 std::getline

Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. and you don't have to worry about the null terminating character and so on. Also it is possible to convert a char array to a string by using the appropriate string contructor.

它使用字符串而不是字符数组。使用字符串更容易,因为它们知道它们的大小,它们会自动增长等,而且您不必担心空终止字符等。也可以使用适当的字符串构造函数将字符数组转换为字符串。

回答by R. Martinho Fernandes

That's an unfortunate historical artifact, I believe.

我相信,这是一件不幸的历史文物。

You can however, use the std::getlinefree function instead.

但是,您可以改用std::getline免费功能。

std::string myText;
std::getline(std::cin,myText);