Incorrect input function

Hey everyone. I'm trying to write a function that reads in a double and checks for incorrect inputs, but it won't let me output the value in main. I have a function that will read in a c-string and check for incorrect inputs, and it will let me output the c-string in main. My question is why would the c-string function hold the value and let me output it to the console but the floating point value is lost? I'm guessing you need to return the value to another variable but it's just weird that one would work and the other doesn't and it's stumping me.

Any help would be appreciated.
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;

//Prototypes
void pause();
void getString(char str[]);
void getInt(int num);
int cmpCstring(char str[]);


//Global Consts
const int MAX_VALUE = 100;
const int MAX_CHAR = 100;

int main()
{
	double total = 0; 
	double cost = 0;
	char product[MAX_CHAR]; 
	int quit = 1;
	
	
	cout << "\nEnter a product: ";
	getString(product);
	quit = cmpCstring(product);
	
	cout << "Enter the cost: ";
	getInt(cost); 

	cout << endl;
	cout << product << " $" << cost << endl; 
	total = cost + total; 
	
	pause();
	return 0;
}



// This function pauses the console.
void pause()
{
	char pause_ch;
	cout << "Press any key to continue... ";
	cin >> pause_ch;
	cin.ignore(MAX_VALUE, '\n');
}

/*
* This function reads in a c-string.
* out: str
*/
void getString(char str[])
{
	cin.get(str, MAX_CHAR, '\n');
	while (!cin)
	{
		cin.clear();
		cin.ignore(MAX_CHAR, '\n');
		cout << "Please enter a string.";
		cin.get(str, MAX_CHAR, '\n');
	}	
	cin.ignore(MAX_CHAR, '\n');
}

/*
* This function reads in an int.
* out: str
*/
void getInt(int num)
{
	cin >> num;
	while (!cin)
	{
		cin.clear();
		cin.ignore(MAX_CHAR, '\n');
		cout << "Please enter a price.";
		cin >> num;
	}	
	cin.ignore(MAX_CHAR, '\n');
}
well, an array implies a pointer to the first element. when you call cin.get() you modify the data pointed to.

the parameter int num of getInt() means you pass by value, i.e. the value will be copied. You can easily call getInt(5).
pass by value also means that the passed parameter num is local to the function and has no effect to the value passed by the caller.

If you want that the modification of a parameter has effect to the variable passed by the caller then you need to pass by reference: void getInt(int &num) // Note the &
This also implies a pointer. Now it would be an error to call getInt(5) because you need to provide a variable where the value can actually be stored
Cool. So just pass by reference and it's good. That helps a lot. Thanks.
Topic archived. No new replies allowed.