探讨数组与字符串输入的问题(C++版)
对于字符串问题,原来理解的不够深刻,现在讨论一些关于字符串输入的问题 1.strlen() 返回的是数组中的字符串的长度,而不是数组本身的长度。 那么更有意思的在后面: char name[16] = "abcdefg"; //输出结果是多少? cout << name << endl; name[3] = ' '; //输出结果又是多少? cout << name << endl; 大家猜猜 ? # include <iostream> # include <cstring> # 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] = ' '; cout << "Here are the first 3 characters of my name : "; cout << name << endl; return 0; } 大家猜猜结果呢? name字符串被截断了... 释义: 不过cin有个缺陷,就是以空白符为结束标志,如果遇到空格和回车就把这个字符串输入完了,这样就需要用能输入一行字符串的方法来解决,但是先看看这个问题: # include <iostream> 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将该字符串放到数组中,并自动在结尾添加空字符' ' 这时如果能输入一行数据,这个问题不就解决了吗? # include <iostream> using namespace std; int main(void) { const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter you name : " << endl; cin.getline(name,ArSize); cout << "Enter you favorite dessert : " << endl; cin.getline(dessert,ArSize); cout << "I have some delicious " << dessert; cout << " for you," << name << endl; return 0; } 释义: cin是将一个单词作为输入,而有些时候我们需要将一行作为输入,如 I love C++ 如果遇到这种情况咋办? # include <iostream> using namespace std; int main(void) { cout << "What year was your house built? " << endl; int year; cin >> year; //char ch; //cin.get(ch); 接收换行符 (cin >> year).get(); cout << "What is its street address ? " << endl; char address[80]; cin.getline(address,80); cout << "Year built : " << year << endl; cout << "Address : " << address << endl; cout << "Done ! " << endl; return 0; } 地址还没有输入,就结束了... 以上就是本文的全部内容,希望对大家的学习有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |