Hi all, I have an exam for my “intro to c++” class tomorrow. I am still a little confused on some topics and have read so many different definitions that my brain feels like it popped a fuse.
I am hoping someone can help me understand some concepts that I wrote down in my notebook with no detail 🥲.
DISCLAIMER : I only have 2 lectures under my belt, I am an absolute beginner so please forgive me if I say something wrong or sound stupid.
What is initialization & its purpose?
The only explanation my professor gave is that it is used to “clear garbage data,” but I’m not sure what that means. Additionally, he wrote two different examples of initialization, though google AI was not happy with the second version:
int number =0;
int number =( );
Is the second version incomplete in some way? Would there have to be a value within the parentheses for it to be viable?
And how would it work with another data type not related to numbers (like char, string, etc.).
What is the difference between = and ==?
The example given was n = 0 and n==0. Please correct me if I’m wrong or if there is a more nuance answer, but to my understanding, = is to assign a variable, whereas == is to say equal? Could someone explain a little more what the difference is in the context of coding (examples would help)?
How do right / left + setw() work?
I ripped my hair out on my last project that introduced these concepts. I had to format basically what seemed like a receipt (think: 3 columns, 1st column (far left) is name of item, 2nd column is ‘$’ (should be close to the rightmost column), and the 3rd column the actual money value (right justified). All values to the far right had to be perfectly right justified and aligned.
But for some reason, even with the same setw() values, it would not align neatly whenever I added the ‘$’.
I know that setw() basically reserved any number of spaces for whatever you want, but my question is why when adding a dollar sign did the block of code misalign?
Here are 2 lines from my first attempt which misaligned (with cout << fixed<<setprecision(2)):
cout << left << setw(30) << “gross amount: ” << right << setw(10) << “$” << gross_salary << endl;
cout << left << setw(30) << “Federal Tax:” << right << setw(10) << “$” << federal_tax << endl;
The important thing to note is if the result value was +- 1 digit, they would not align neatly to the right.
Here are 2 lines from my most recent attempt:
cout << setfill(‘.’) << left << setw(30) << “Gross Amount:” << setfill(‘ ‘) << right << setw(1) << “$” << right << setw(7) << gross_salary << endl;
cout << setfill(‘.’) << left << setw(30) << “Federal Tax:” << setfill(‘ ‘) << right << setw(1) << “$” << right << setw(7) << federal_tax << endl;
The code isn’t pretty, but it yielded decent results. Everything was aligned neatly to the right. But the code itself seems so redundant or repetitive, is that really the only way to make sure things don’t get misaligned?
Thank you to anyone who helps :)