How to end this cycle correctly?
I'm trying to create a program where the user asks for a number that I will eventually figure out, but if the user has to enter "x", the loop ends. I don't have much, but if I run this program and type "x" it is warped because the data type it is looking for is double, so it doesn't work the way I want it to. Is there an alternative way than the one I have here to do this so that the loop ends instead of shutting down the program?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//function
//main function
int main()
{
//variables
double n1, n2;
//input
do {
cout << "Enter the first number \n";
cin >> n1;
cout << "Enter the second number \n";
cin >> n2;
//output
} while (true);
return 0;
}
source to share
You can compare with n1
or n2
with x
(string). If one of them is equal x
, then end the loop.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
//function
//main function
int main()
{
//variables
string n1, n2;
double n3, n4;
//input
do {
cout << "Enter the first number \n";
cin >> n1;
cout << "Enter the second number \n";
cin >> n2;
if(n1 == "x" || n2 == "x"){ // n1 or n2 with "x" .
break;
}
n3 = stod(n1); // string to double.
n4 = stod(n2);
//output
} while (true);
return 0;
}
source to share
Let the input values ββbe strings and then convert them to char arrays, then you can check the first element in the array if it is x, if any, break. Then you can do whatever you want after converting it to double.
string n1, n2;
do {
cout << "Enter the first number \n";
cin >> n1;
cout << "Enter the second number \n";
cin >> n2;
char[] n1Array = n1.toCharArray();
if (n1[0] == 'x') break;
char[] n2Array = n2.toCharArray();
n1Double = atof(n1Array);
n2Double = atof(n2Array);
//output
} while (true);
I think he should do it.
source to share