C++ do while循环/c++;
我有一个程序要写:写一个程序,用户输入数字,直到输入“e”或“e”。用户在控制台上输入和写入的所有数字。 到目前为止,我写了这些,但我不知道当“e”或“e”输入时如何打破循环!?如果有人能帮我的话C++ do while循环/c++;,c++,visual-c++,C++,Visual C++,我有一个程序要写:写一个程序,用户输入数字,直到输入“e”或“e”。用户在控制台上输入和写入的所有数字。 到目前为止,我写了这些,但我不知道当“e”或“e”输入时如何打破循环!?如果有人能帮我的话 #include<iostream> using namespace std; void main() { int sum=0, number=0; do { cout << "Enter a number: \n";
#include<iostream>
using namespace std;
void main()
{
int sum=0, number=0;
do
{
cout << "Enter a number: \n";
cin >> number;
sum+=number;
} while (don't know what to type here);
cout << "Sum = " << sum << endl;
}
#包括
使用名称空间std;
void main()
{
整数和=0,数字=0;
做
{
数量;
总和+=数字;
}while(不知道在这里输入什么);
cout您应该让程序接受字符串作为输入,然后尝试将该字符串转换为整数
#include<iostream>
using namespace std;
int main() {
int sum = 0;
string number;
while (true){
cout << "Enter a number: ";
cin >> number;
if (number.length() == 1 && (number.at(0) == 'E' || number.at(0) == 'e')) break;
const char* data = number.c_str();
char* end = (char*)data + number.length();
int value = strtol(data, &end, 10);
sum += value;
};
cout << "Sum = " << sum << endl;
return 0;
}
#包括
使用名称空间std;
int main(){
整数和=0;
字符串编号;
while(true){
数量;
如果(number.length()==1&&(number.at(0)='E'| | number.at(0)='E'))中断;
const char*data=number.c_str();
char*end=(char*)数据+number.length();
int值=strtol(数据和结束,10);
总和+=数值;
};
所以请试试这段代码
#include<iostream>
using namespace std;
int main()
{
int sum = 0, number = 0;
while (true)
{
cout << "Enter a number: \n";
if (cin >> number) sum += number;
else break;
}
cin.clear(); //reset the state of cin
char ch;
cin >> ch;
if (!(ch == 'e' || ch == 'E'))
{
cout << "Invalid input!" << endl;
system("pause");
return 0;
}
cout << "Sum = " << sum << endl;
}
#包括
使用名称空间std;
int main()
{
整数和=0,数字=0;
while(true)
{
cout>数字)总和+=数字;
否则就断了;
}
cin.clear();//重置cin的状态
char ch;
cin>>ch;
if(!(ch='e'| ch='e'))
{
无法查找do..while()
的工作方式,然后重试“不知道在这里键入什么”--您需要插入一个布尔表达式,测试某个变量是否相当于'e'
或'e'
@Michael:这与的工作方式无关。..while()
有效。@Marko,如果要检测字母,首先需要从读取字母开始;目前,您只读取int
@Marko您的变量称为number
notletter
。意思是number的值不是字母。@JamesAdkison不起作用;操作符>
用于int
收到信件时将进入错误状态这一切正常,除非我启动程序并输入例如5和5,然后“e”我得到的结果和是15。@M.M,如果可以,谢谢,现在看来一切正常。std::stoi(数字)
比您设置的strtol
要简单一些当我试图编译时,“cin>>number”中有一个错误