。
#include <iostream>
#include <stdlib.h>
using namespace std;
int i;
int e;
int p;
char name[10] = {};
cout<<endl<<"Please enter the letters of your name separated by enter, when you are done, type 'quit' "<<endl;
for (e=0; e <= 10; e++)
{
cin>>name[e];
if (name[e] == 'quit')
{
break;
}
}
for (p=0; p < ; p++)
{
cout<<name[p];
}
return 0;
}
我希望用户输入的名称不超过 10 个字符,但如果用户输入 quit,我想结束循环。请帮助解决我的问题。提前谢谢。
像这样做 -
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
int i;
int e;
int p;
vector<string> name;
cout<<endl<<"Please enter the letters of your name separated by enter, when you are done, type 'quit' "<<endl;
while(1)
{
string tmp;
cin>>tmp;
if (tmp == "quit")
{
break;
}
else if(tmp.size()>10)
{
cout<<"Enter name with less then 11 character"<<endl;
}
else
{
name.push_back(tmp);
}
}
for (auto n : name)
{
cout<<n<<endl;
}
return 0;
}
为此使用 getline 。此外,使用std::string来收集数据并检查输入的大小也会更容易
"quit" 是一个字符串,它包含 4 个字符。 不能将其视为单个字符。 因此,您必须使用双引号 " 而不是单引号 ''。此外,此字符串保存在字符数组中,而不是单个 char 变量中。所以
if (name[e] == 'quit')
是完全错误的。