C++问题八:C-style与string的区别与联系。分别利用这两种方式实现同样的操作。
区别:
C-style :是C语言风格字符串,它是一个指针或者是一个char数组,字符串的末尾有\0字符。
string:C++标准库定义了string类,头文件为#include。该文件下提供了大量的字符串操作函数并且可以与C-style相转换。string本质上是以字符作为元素的vector(容器)的特化版本。不存在0字符结尾这个概念。
通过c_str()或data()把string转化为c-style时,结尾会是\0。
c-style实现用户输入用户名,用户名大于两个字符,提示输入正确,并将用户名输出,用户名输出错误,提示用户输入错误并再次输入直至用户输入正确为止。
#include<iostream>
#include<iomanip>// setw(size) 的头文件
#include<string>
using namespace std;
int main()
{
const int size = 50; //size为const int 该值不能改变。
char user_name[size];
cout << "请输入您的姓名:" << endl;
cin >> setw(size) >> user_name;
for (; strlen(user_name) < 2;)
{
cout << "输入格式不合法,请重新输入" << endl;
cin >> setw(size) >> user_name;
}
cout << "您输入的格式合法,您的名字为:" << endl;
cout << user_name << endl;
system("pause");
return 0;
}
结果如下
string实现用户输入用户名,用户名大于两个字符,提示输入正确,并将用户名输出,用户名输出错误,提示用户输入错误并再次输入直至用户输入正确为止。
#include<iostream>
//#include<iomanip>
#include<string>
using namespace std;
int main()
{
string str;
cout << "请输入您的姓名:" << endl;
cin >> str;
for (; str.length() < 2;)
{
cout << "输入格式不合法,请重新输入" << endl;
cin >> str;
}
cout << "您输入的格式合法,您的名字为:" << endl;
cout << str << endl;
system("pause");
return 0;
}
结果如下