String字符串输入经常会遇到下面的情况:
#include<iostream>
#include<windows.h>
#include<string>
using namespace std;
int main()
{
string food;
cout << "你喜欢吃什么?" << endl;
cin >> food;
cout << "你最喜欢吃的美食有" << food <<endl;
system("pause");
return 0;
}
可以发现当我们输入连续几个字符串,中间有空格区分时,空格后面的内容不会显示。
#include<iostream>
#include<string>
#include<windows.h>
using namespace std;
//连续输入多个字符串,而且输入的字符串个数不确定。
//直到输入结束时(Ctrl+z并回车)
int main()
{
string food; //食物
int count=0;
//cout << "你喜欢吃什么?";
//需要使用循环语句
//使用cin>>输入时,如果遇到文件结束符(Ctrl+z),就返回0
while (cin >> food)
{
count = count + 1;
cout << "你最喜欢的第" << count << "种美食是:" << food << endl;
cout << "你还喜欢吃什么?";
}
cout << "你最喜欢吃的美食有" << count << "种" << endl;
system("pause");
return 0;
}
我们可以加一个while循环:while(cin>>food),这样就可以连续输入,当输入结束时按Ctrl+z后按回车,循环结束。
#include<iostream>
#include<string>
#include<windows.h>
using namespace std;
int main()
{
string addr;
cout << "你准备去哪里旅游啊?" << endl;
getline(cin, addr); //读一行,从标准输入设备(cin)读取一行字符串,保存到字符串变量addr中
//如果用户直接回车,就没有任何数据输入
//直到遇到回车符,注意不包括回车符
if (addr.empty() == true) //empty:判断输入的字符串是否为空串.如果是空字符串,结果是true,否则结果是false
{
cout << "你输入了一个空串!" << endl;
}
else
{
cout << "太巧了,我也准备去" << addr << "旅游" << endl;
}
//计算字符串的长度:
cout << "地址的长度是:" << addr.size() << endl;
cout << "地址的长度是:" << addr.length() << endl;
//size()和length()效果是一样的
system("pause");
return 0;
}
可以发现六个汉字加两个空格长度为14,因为汉字占两个字节(有的编译器占3个字节,此编译器为VS2013),空格占一个字节.