C++学习字符串输入的小例子,并且做了一些字符串是否为空,字符数组转换为字符串的一些操作。
下面是例子:在DEV C++的编译工具下面顺利通过编译
#include <iostream> #include<string> using namespace std; int main(){ int count = 20; char name[count]; char password[count]; bool isExit=false; int timeOut=0; while(!isExit) { cout <<"请输入用户名:"<<endl; cin>>name; cout <<"请输入密码:"<<endl; cin>>password; string name1=string(name); string password1 = string(password); if(timeOut==5){ isExit=true; cout <<"登录失败5次!账户已锁定"<<endl; return 5; } if(!name1.empty()&&name1=="admin" && !password1.empty()&& password1=="123456"){ cout <<"登录成功!"<<endl; timeOut=0; }else{ timeOut++; cout <<"登录失败"<<endl; } cout <<"----------------------------"<<endl; cout<<"\r\n"<<endl; } return 0; }
上述方式不能接受带空格的字符串,如果字符串中有空格会截取的。所以我们想获取带空格的字符串那就必须要获取一行的下面我们来尝试的写写接受带空格的字符串吧。
代码如下:
#include <iostream> using namespace std; int main(){ int SIZE=30; char name[SIZE]; char password[SIZE]; cout <<"请输入用户名:"<<endl; cin.getline(name,SIZE); cout <<"请输入密码:"<<endl; cin.getline(password,SIZE); cout <<name<<endl; cout <<password<<endl; return 0; }
上面输入内容时你可以在字符串之间添加空格和上面的例子做个对比就知道了。