Void functions and variables

Hi I'm fairly new to C++ and programming in general and I'm trying to get a program to check the parameters of a binary string before converting that string to dec values. I have the user input 'num' line 39 - 42, but I want to reuse that same value in the 'void bin_to_dec()' function. Is there anyway I can use the same variable between void functions?

Thanks!

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
42
43
44
45
46
 

 13 #include <bitset>
 14 #include <sstream>
 15 using namespace std;
 16
 17 void dec_to_bin(){
 18         string mess;
 19
 20         cout << "Please enter a phrase: "; //prompt
 21         getline(cin, mess);     //getline used for accepting ' ''s in strings
 22         cout << "Your message was:              " << mess <<endl;
 23
 24         for(int i = 0; i < mess.length(); i++){
 25                 cout << mess.at(i) << "\n" << bitset<8>(mess.at(i)) << endl;}
 26 }
 27
 28 void bin_to_dec(){
 29         string num;
 30
 31         istringstream in(num);
 32
 33         bitset<8> bits;
 34         while (in >> bits)
 35                 cout << char(bits.to_ulong());
 36         cout << "\n";
 37 }
 38
 39 void check_bin_nums(){
 40         string num;
 41         cout << "Please enter a binary string: ";
 42         getline(cin, num);
 43
 44         for (int i=0; i < num.length(); i++){
 45                 if (num.at(i) == '1' || num.at(i) == '0' || num.at(i) == ' ')
 46                         bin_to_dec();
 47                 else
 48                         cout << "Error: Unknown character detected." << endl;
 49                         break;
 50         }
 51 }
 52 int main(){
 53
 54         dec_to_bin();
 55         check_bin_nums();
 56 }
Last edited on
You can make bin_to_dec() accept num as a parameter and pass it to it.

Alternatively, you could read the string in main() (i.e., move lines 40~42 into main) and pass the string num into each of those functions as a parameter. However, you may want to make check_bin_nums() actually report whether the string is valid (probably by returning a boolean) so you don't try to then use bin_to_dec() on an invalid string.
"void function" is incorrect terminology, by the way. You can say "void-returning function" or "function with no return value", but don't say "void function".
Thank you guys, I got it using the alternative method above.

And thanks LB, I'll be sure to remember that in the future.
Topic archived. No new replies allowed.