简体   繁体   中英

Char array with cin.getline()

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?

Use cin.getline(CDdata[count].title, 1000) . The second parameter is the length of your char array, 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.

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

If you want a more formal description, read here .

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

使用cin.getline()因为它将'\\n'作为终止字符而不是空格。

在此处输入图片说明

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

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