C++ Loop

closed account (SwAfjE8b)
Hello Everyone!

So it's been a while since I have coded so this might be a silly question. I am trying to create a loop that asks the user to "Enter an integer or DONE to stop". How can I mix the int and string? And also what loop would be best? I tried the while and do-while but neither of them worked. Any help would be appreciated. Below is my code thus far:

std::cout << "--- Welcome to the Number Conversion Answer Generator ---" << std::endl;
std::cout << "Enter the filename for the data:" << std::endl;
getline(std::cin, fileName);

file.open(fileName.c_str());

std::cout << "Enter an integer, or DONE to stop:" << std::endl;
std::cin >> response;

file << response << std::endl;
Last edited on
You would want to use string. Since string can hold digits too, then you can use this function to find out where there is an digit or not. I even added an extra condition to check if the second character is a dot or not. Because if the second character is a dot, the response could be 2.5, or 6.2, which would make it not an integer. Note that the user can still enter something like 55.5, which the program would not catch. but if you want to check all the characters to make sure there is no dot then it would be a bit more work than this.

You can use the function isdigit() // http://www.cplusplus.com/reference/cctype/isdigit/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int main()
{
	std::string response;
	bool OK = true;
	do
	{
		std::cout << "Enter an integer or DONE to stop" << std::endl;
		std::cin >> response;

		if (response == "DONE" || (isdigit(response[0]) && response[1] != '.'))
			OK = false;

	} while (OK); // runs while OK == true
}


In the condition for the do-while loop. I have told it to keep running while response does not equal DONE, making it stop when it does equal DONE.
And the second condition is that the first character in the string is a digit, and the second character is not a dot. If the first character in the string is a digit, then you obviously know it is some kind of number.

Hope this helps!
Last edited on
closed account (SwAfjE8b)
Thank you so much!
Topic archived. No new replies allowed.