一,使用读取一行字符串的变量getline
demo1:
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main(void) {
string addr;
cout << "美女,你要到哪里去啊?";
//从标准输入设备(cin)读取一行字符串,保存到字符串变量addr
//读取一行,直到遇到回车符,但不包括回车符
//如果用户直接回车,就没有任何数据输入
getline(cin,addr);
cout << "太巧了,我也要到" << addr << endl;
system("pause");
return 0;
}
语句getline(cin,addr);作用为:
从标准输入设备(cin)读取一行字符串,保存到字符串变量addr。读取时,直到遇到回车符才停止,但不包括回车符。假如用户直接回车,就没有任何数据输入。
注意:
1.如果在getline(cin,addr);语句之前加上"cin >> addr",那么控制台输出的只会是第一个空白字符之后的字符串,包括第一个空白字符。假如用户输入一个字符串之后直接回车,那么此时控制台就没有任何数据输入。
2.如果用户直接回车,就没有任何数据输入。解决办法在demo2。
二,使用函数empty()判断输入的字符串是否为空串:
demo2:
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main(void) {
string addr;
cout << "美女,你要到哪里去啊?";
getline(cin,addr);//读取一行,直到遇到回车符,但不包括回车符
//empty()判断一个字符串是否为空
if(addr.empty() == true) {//如果字符串变量addr是空为真
cout << "你输入了一个空串" << endl;
} else {
cout << "太巧了,我也要到" << addr << endl;
}
//计算字符串的长度
cout << "addr的字节长度:" << addr.length() << endl;
cout << "addr的字节长度:" << addr.size() << endl;
system("pause");
return 0;
}
函数empty()可以判断一个字符串是否为空