I'm trying to write a code to determine whether a number is a "happy" number or not, this is the code I developed. Originally did it with the main function and then a function bool isHappy(unsigned int n), but I got the following error when compiling, which I'm still getting:
jcwa@Adkins-MSI:/mnt/d/code/exam1$ g++ -std=c++17 happy.cpp happy.cpp
/tmp/ccRfdsUm.o: In function `main':
happy.cpp:(.text+0x0): multiple definition of `main'
/tmp/cczezbZD.o:happy.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
#include <iostream>
#include <vector>
using std::cin, std::cout, std::endl, std::vector;
int main() {
cout << "Enter a number to check for happiness: " << endl;
unsignedint n;
cin >> n;
vector<int> nums(0);
int orig = n;
bool happy = 0;
int length = 0;
int sqSum;
for (int i = 0; n > 10; n/= 10) {
nums.push_back(n % 10);
length++;
int check = n / 10;
if (check <= 10) {
nums.push_back(check);
length++;
for (int j = 0; j < length; j++) {
sqSum += nums.at(j)*nums.at(j);
}
if (sqSum == 1) {
happy = 1;
} elseif (sqSum == orig) {
happy = 0;
} else {
n = sqSum;
}
}
}
if (happy == 1) {
cout << n << " is a happy number." << endl;
} else {
cout << n << " is not a happy number." << endl;
}
return 0;
}
I haven't been able to do any testing to see if this code would actually work since I can't compile it, so I'm not looking for help with that, but why am I getting the multiple definitions error? This .cpp is saved in its own folder by itself.
By the way, once you get past the compiler errors:
1 2 3
In function 'int main()':
15:14: warning: unused variable 'i' [-Wunused-variable]
23:47: warning: 'sqSum' may be used uninitialized in this function [-Wmaybe-uninitialized]
Alright thanks I feel like an idiot now I was just confused by the way I was instructed to compile the first code that I made. It was never really explained to me very well how you're supposed to compile code, I was just given 1 example and was trying to figure it out based off of that. They made me compile the first code I wrote by typing "g++ -std=c++17 -o hello_world hello_world.cpp" so I thought you had to say the name of the file twice although I didn't know why. Still don't know what was going on there really. At least this issue is cleared up, thanks again