String issues

Dec 3, 2014 at 1:32pm
I'm confused. I can't seem to get the largest and smallest numbers to output. What did I do wrong? ( I want to follow this format )

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
  #include <iostream>
using namespace std;

void findLargest(string text);
void findSmallest(string text);

int main()
{
	const int LENGTH = 100;
	char s[LENGTH];
	int total = 0, index;
	cout << "Enter a series of numbers in a row " << endl;
	cin >> s;
	for (index = 0; index < strlen(s); index++)
	{
		total += s[index] - '0';
	}
	cout << "The total is " << total << endl;
	cout << "The largest number is ";
	findSmallest(s);
	cout << "The smallest number is ";
	findLargest(s);
	return 0;
}
void findSmallest(string text)
{
	char smallestNum;
	for (int a = 0; a < sizeof(text); a++)
	{
		if (a == 1)  smallestNum = text[1];
		if (text[a] < smallestNum) smallestNum = text[a];
	}
	cout << smallestNum;
}

void findLargest(string text)
{
	char largestNum;
	for (int a = 0; a < sizeof(text); a++)
	{
		if (a == 1)  largestNum = text[1];
		if (text[a] >largestNum) largestNum = text[a];
	}
	cout << largestNum;
}
Dec 3, 2014 at 1:40pm
1
2
if (a == 1)  smallestNum = text[1];
if (a == 1)  largestNum = text[1];


Remember arrays start at 0(zero), these two lines are setting smallest/largestNum to the second element in text
Last edited on Dec 3, 2014 at 1:41pm
Dec 3, 2014 at 2:06pm
Line 28, 39: sizeof(text) does return the entire size of the string object text, which may contain sizes of some internal attributes of string. Use length() instead, which reports the number of actual characters of a string: text.length()
Dec 3, 2014 at 9:24pm
Thank you so much! I see what I was doing wrong!
Topic archived. No new replies allowed.