Defining a variable in a loop

Hi Guys,

Does defining a variable in a loop cause issues when you refer to that variable outside of the loop?

In the following code, it appears to...

Try typing "asd" first.
Then try typing "123.4"

For cout #2 and #3, I get a value of "0".

If I type "123abc" first
Then "123.4"

For cout #2 and #3, I get the first value of "123"

Anyone know why?

Finally, would anyone know of a way to have input checked to see whether it ONLY
contains integers? For example, "1234" would be accepted but "abc1234", "1234abc" or "1234.1" would be rejected? I feel like I am taking an overly complicated route to TRY and achieve this at present ;)

Thank you!

Kind Regards,

Giri

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>

int main (void)
{
	using namespace std;

	cout << "Contributions to the Society for the Preservation of Rightful Influence" << endl;
	cout << "Please enter the number of Contributors" << endl;
	
	string noContributors;
	char * endString;
	
	getline(cin,noContributors);

	double noContributorsDouble = strtod(noContributors.c_str(), &endString);

		while (*endString != NULL)  
			{
				cout << "Please enter a valid integer" << endl;
				noContributors.clear();
				getline(cin,noContributors);
				double noContributorsDouble = strtod(noContributors.c_str(), &endString);
				cout << "1) " << noContributorsDouble << endl;					
			}
		
		cout << "2) " << noContributorsDouble << endl;
		int noContributorsInt = noContributorsDouble;	
		cout << "3) " << noContributorsInt << endl;
		cout << noContributorsInt << " people have donated money" << endl;


		cin.get();


		return 0;

}
If you declare a variable inside a loop, then you cannot use that variable outside the loop because it is destroyed once you leave the loop. This is great for helping to keep programs smaller since you only use space as you need it.

As for detecting if input is a number or not, you could use cin and that would only accept integers if you put it into an integer, but you also would have the problem that abc1553 would be 1553. If you are using a Window and not a console, you could create and Edit box that doesn't allow these characters, as for consoles, you could just loop until there are only numeric characters in the input.
Thanks for the that William!

With regards to the second part of your response, how could I go about checking that the input ONLY contained numeric characters?

Also for example, if I did want to use a counter from within a loop outside of that loop, how could I do that?

Kind Regards,

Giri
Sorry, missed this! You could put it inside a loop and keep asking for input until you detected that the proper input was given.
Topic archived. No new replies allowed.