string of Cpp

本文详细解释了C++中字符串的输入方法及其结束符的使用,包括如何利用空格、换行等字符作为分隔符,以及如何通过`getline()`和`get()`函数来读取输入行,并解决在读取输入时遇到的新行字符问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The last character of every string is the null character. This character, written \0, is the character with ASCII code 0, and it serves to mark the string’s end.
The way to create a string in C++ is like that:

char bird[10] = “Mr. Cheeps”;// the \0 is understood
char fish[] = “Bubbles”;     // let the compiler count
If you want to indicate the length of the string,that you should make sure the array is large enough to hold all the characters of the string, including the null character.
char shirt_size = “S”;       // illegal type mismatch
Because of the "S" is just a string which have a ending char '\0', that you can't assign a char array to a char.

The problem lies with how cin determines when you’ve finished entering a string. You can’t enter the null character from the keyboard, so cin needs some other means for locating the end of a string. The cin technique is to use whitespace—spaces, tabs, and newlines—to delineate a string.  

you need a line-oriented method instead of a word-
oriented method. You are in luck, for the iostream class, of which cin is an example, has some line-oriented class member functions: getline() and get(). Both read an entire input line—that is, up until a newline character. However, getline() then discards the newline character,whereas get() leaves it in the input queue.
Because the first call leaves the newline character in the input queue, that newline character is the first character the second call sees. Thus, get() concludes that it’s reached the end of line without having found anything to read. Without help, get() just can’t get past that newline character.
The get() function will leave the '\n' char to the queue of the input, thus the get() function that suppose to get a string after a string just get one, will get noting.

then you should add a get() after where there must be a 'Enter'.

 

转载于:https://www.cnblogs.com/henyihanwobushi/archive/2012/09/05/2671208.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值