C++ 带有 cin.getline() 的字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17017563/
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-27 20:49:58  来源:igfitidea点击:

Char array with cin.getline()

c++

提问by LeverArch

I'm doing an assignment where we aren't allowed to use strings, we have to use char arrays. This is my code:

我正在做一个不允许使用字符串的作业,我们必须使用字符数组。这是我的代码:

cout << "Enter Album name: ";
cin >> CDdata[count].title;     
fout << CDdata[count].title;

the problem is that when I enter something with a space in it, the rest of my code gets screwed up.

问题是当我输入带有空格的东西时,我的其余代码就会被搞砸。

How do I get it so that I can enter something with a space in it?

我如何获得它以便我可以输入带有空格的东西?

回答by vidit

Use cin.getline(CDdata[count].title, 1000). The second parameter is the length of your char array, CData[count].title.

使用cin.getline(CDdata[count].title, 1000). 第二个参数是字符数组的长度,CData[count].title

The above function either reads 1000 characters or until it finds a delimiter, which is by default a newline (\n) but can be changed as follows.

上面的函数要么读取 1000 个字符,要么直到找到一个分隔符,默认情况下它是一个换行符 ( \n),但可以按如下方式更改。

 cin.getline(CDdata[count].title, 1000, ',') //delimiter is changed to ','

If you want a more formal description, read here.

如果您想要更正式的描述,请阅读此处

P.S:I have used 1000, second argument, as a placeholder. You should change it accordingly.

PS:我使用了 1000,第二个参数,作为占位符。你应该相应地改变它。

回答by Asha

Use cin.getline()as it will '\n'as the terminating character and not space.

使用cin.getline(),因为它会'\n'为终止字符,而不是空间。

回答by Sohaib Shahidulhaq

enter image description here

在此处输入图片说明

when cin.getline() is escaping some thing its bc of some previous data in buffer that we can clean by cin.ignore() it escape the first caracter while reading from buffer

当 cin.getline() 正在转义缓冲区中一些先前数据的 bc 时,我们可以通过 cin.ignore() 清除它在从缓冲区读取时转义第一个字符