3

I'm attempting to make a program where it asks the user to enter a number that I will eventually compute, but if the user were to enter a "x" the loop would end. I don't have much but if I run this program and type in a "x" it bugs out because the data type it is looking for is a double so it doesn't work the way I want it. Is there an alternate way than the way I have it here to make it so that the loop will end instead of the program bugging out?

#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; } 
3
  • 2
    Compare whatever user enters with that certain "x" and break? Commented Jul 23, 2017 at 5:51
  • 1
    You can read the input into a string variable, and parse it manually. Commented Jul 23, 2017 at 5:51
  • if(cin >> n1) will be false if they do not enter a number. Commented Jul 23, 2017 at 5:59

2 Answers 2

1

You can compare n1 or n2 with x(string) . If one of them is equal to x then terminate 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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Let the input values be strings, then convert them to char arrays, then you can check the first element in the array if it's an x, if it is, break. Then you can do whatever you need to do after converting it to a 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 that should do it.

1 Comment

i couldnt seem to use this correctly. Also char[] n1Array; to initialize a array doesnt work but char n1Array[]; does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.