So I have a text file with students names. I made a struct with first names, last names, and grade. I'm supposed to sort the names by last name. The way I sorted works when the last name is defined as a string, but I need to define it as char lastname[50]. And when I do that, it doesn't sort.
for (int i = 0; i < 20; i++)
{
for (int i = 0; i < 20; i++)
You need different loop variables.
You can't use i for both, and expect it to do what you want.
> if (s[i].lastname > s[i + 1].lastname)
This would be fine, if you'd used std::string as your data type.
But as it stands, you need to use strcmp() instead.
> swap(s[i], s[i + 1]);
Is this std::swap, or some random thing you wrote?
If it's your thing, are you parameters reference (good) or value (bad)?
> I also changed the loop variables and it outputed the names correctly, but not in the order I wanted:
But you didn't fix your nested loop variables!
1 2 3 4 5 6 7 8
$ g++ -Wall -Wextra -Wshadow bar.cpp
bar.cpp: In function āint main()ā:
bar.cpp:28:14: warning: declaration of āiā shadows a previous local [-Wshadow]
for (int i = 0; i < 20; i++)
^
bar.cpp:26:10: note: shadowed declaration is here
for (int i = 0; i < 20; i++)
^
> I understand that I need to use strcmp(), but I'm not sure how to implement it in my function.
Did you read keskiverto's link?
I mean, it has an example and everything.
At least enough for you to make an attempt.