如何在输入整数时中断 for 循环
How to break a for loop when an integer is entered?
#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')
是完全错误的。
相关文章:
- "error: no matching function for call to"构造函数错误
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何在C++中从两个单独的for循环中添加两个数组
- 在Linux for Windows上编译C++代码时出错
- 调用专用模板时出错"no matching function for call to [...]"
- 为什么我的for循环不能正确获取argv
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 螺旋矩阵在最后一个"for"循环中中断,不显示任何内容
- 我的 break 语句没有中断 for 循环
- 如何在输入整数时中断 for 循环
- 在 for 循环中使用中断
- 如何仅针对此特定值中断 for 循环
- OpenCV/ c++ for循环不会中断
- 一次执行后,嵌套for循环出现意外/未见的中断:高斯消去
- c++在几个for循环中中断
- C++for循环逻辑:从cmdline参数中获取字符串后中断
- 如何中断for循环