I urge you to make these changes one at a time and test your program after each one. Then save the program to a different file and move on to the next change.
All line numbers below refer to the original line in your last past unless otherwise stated.
1. The only include files you need are iostream and string so delete lines 3-6.
2.
Develop a program to determine whether or not the following numbers are divisible by 9 |
Your program doesn't really do that. It just prints out a bunch of numbers that the user must interpret. I suggest you change div to return a bool that says whether the number is divisible by 9:
- change line 9 to
bool div(string, char &, int &, int &);
- change line 27 to
bool div(string data, char& digit, int& num, int& combo)
- change line 42 to
return (combo % 9 == 0);
3. Now that div returns a bool, you can output the right thing. Change lines 20 & 21 to
1 2 3 4 5
|
if (div(data, digit, num, combo)) {
cout << data << " is divisible by 9\n";
} else {
cout << data << " is not divisible by 9\n";
}
|
4. Keep your data local. Variables digit, num and combo are only used in div(), so they should be declared there. This has the added benefit of needing fewer parameters in div:
- move lines 13-15 to right after line 29.
- Change line 9 to
bool div(string);
- Change line 27 to
bool div(string data)
- Change the call to div at line 1 in change number 3 above to
if (div(data)) {
5. It's handy to think of loops as two different parts of code. There's the code that controls the loop, and the code that does something for each iteration. I like to use
for
loops whenever possible because they help to separate those two distinct bits of code. Look at div(): the code that controls the loop is at lines 29, 30, 33, and 40. It would be better to put all of that together:
1 2 3
|
for (int counter = 0; counter < data.size(); ++counter) {
...
}
|
If you've learned about range-based for loops, then it's even easier:
1 2 3
|
for (char digit : data){
...
}
|
As I mentioned earlier, let the compiler do the cast conversions for you so change line 35 to:
num = digit - '0';
. Better still, why have a separate digit variable at all? Get rid of digit and change line 35 to
num = data[counter] - '0';
6. Line 37 is debugging code. Delete it.
7. Right now you're copying the string to div. That's wasteful. It would be better to pass a reference (or a const reference if you've learned about those). For a simple reference:
- change line 9 to
bool div(string &);
- change line 27 to
bool div(string &data)