c语⾔⽤cin输⼊字符数组,探讨数组与字符串输⼊的问题
(C++版)
对于字符串问题,原来理解的不够深刻,现在讨论⼀些关于字符串输⼊的问题
1.strlen() 返回的是数组中的字符串的长度,⽽不是数组本⾝的长度。
2.strlen()只计算可见的字符,⽽不把空字符计算在内。
c语言如何创建字符串数组那么更有意思的在后⾯:
char name[16] = "abcdefg";
//输出结果是多少?
cout << name << endl;
name[3] = '\0';
//输出结果⼜是多少?
cout << name << endl;
⼤家猜猜 ?
# include
# include
# define SIZE 15
using namespace std;
int main(void)
{
char name_cin[SIZE];
char name[SIZE] = "C++owboy"; //initialized array
cout << "Hello I'm " << name;
cout << "! What is your name ? ";
cin >> name_cin;
cout << "Well " << name_cin << ", your name has ";
cout << strlen(name_cin) << " letters and is stored " << endl;
cout << "in an array of " << sizeof(name_cin) << "bytes." << endl;
cout << "your initial is " << name_cin[0] << "." << endl;
name[3] = '\0';
cout << "Here are the first 3 characters of my name : ";
cout << name << endl;
return 0;
}
⼤家猜猜结果呢?
name字符串被截断了...
释义:
数组可以⽤索引来访问数组的各个字符,例如name[0]到数组的第⼀个字符,name[3] = '\0';  设置为空字符,使得这个字符串在第三个字符后⾯即结束,即使数组中还有其他字符。
不过cin有个缺陷,就是以空⽩符为结束标志,如果遇到空格和回车就把这个字符串输⼊完了,这样就需要⽤能输⼊⼀⾏字符串的⽅法来解决,但是先看看这个问题:
# include
using namespace std;
int main(void)
{
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name : " << endl;
cin >> name; //输⼊名字
cout << "Enter your favorite dessert: " << endl;
cin >> dessert; //输⼊甜点的名字
cout << "I have some delicious " << dessert;
cout << " for you, " << name << "." << endl;
return 0;
}
释义:
cin使⽤空⽩(空格、制表符、换⾏符)来定字符串的边界,cin在获取字符数组输⼊时只读取第⼀个单词,读取单词后,cin将该字符串放到数组中,并⾃动在结尾添加空字符'\0'
cin把Meng作为第⼀个字符串,并放到数组中,把Liang放到输⼊队列中第⼆次输⼊时,发现输⼊队列Liang,因为cin读取Liang,并将它放到dessert数组中
这时如果能输⼊⼀⾏数据,这个问题不就解决了吗?
getline()、get()可以实现...
# include
using namespace std;
int main(void)
{
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter you name : " << endl;
cout << "Enter you favorite dessert : " << endl;
cout << "I have some delicious " << dessert;
cout << " for you," << name << endl;
return 0;
}
释义:
cin是将⼀个单词作为输⼊,⽽有些时候我们需要将⼀⾏作为输⼊,如 I love C++
iostream中类提供了⼀些⾯向⾏的类成员函数,如getline()和get(),这两个都是读取⼀⾏的输⼊,直到换⾏符结束,区别是getline()将丢弃换⾏符
get()将换⾏符保留在输⼊序列中
⾯向⾏的输⼊:getline(char* cha,int num)
getline()读取整⾏,通过换⾏符来确定结尾,调⽤可以使⽤ line(char* cha,int num),成员函数的⽅式使⽤,第⼀个参数是⽤来存储输⼊⾏的数组的名称,第⼆个参数是要读取的字符数,如果这个字符数的参数为30,则最多读⼊29个字符,余下的⽤于存储⾃动在结尾处添加的空字符。
get()存储字符串的时候,⽤空字符结尾。
如果遇到这种情况咋办?
# include
using namespace std;
int main(void)
{
cout << "What year was your house built? " << endl;
int year;
cin >> year;
//char ch;
//(ch); 接收换⾏符 (cin >> year).get();
cout << "What is its street address ? " << endl;
char address[80];
cout << "Year built : " << year << endl;
cout << "Address : " << address << endl;
cout << "Done ! " << endl;
return 0;
}
地址还没有输⼊,就结束了...
去掉上⾯的注意,加⼀个字符,接收换⾏符就可以了...
注:C++程序常使⽤指针⽽不是数组来处理字符串
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。