C Question I have a text file that contains data from a CD e
C++ Question
I have a text file that contains data from a CD (ex 1. Adagio “MoonLight” Sonata - Ludwig Van Beethoven /n 2. An Alexis - F.H. Hummel and J.N. Hummel)
How do I sort the data by author since that information is in the middle of the string?
Here\'s what I have that sorts the string from the beginning:
if (file.is_open())
{
while (getline(file, line))
{
lines.push_back(line);
}
}
else {
cout << \"Could not open file\" << endl;
}
for (int i = 0; i < lines.size(); i++)
{
//code
sort(lines.begin(), lines.end()); //sorts from beginning (song)
for (int i = 0; i < lines.size(); i++)
cout << lines[i] << \"\ \";
Need help sorting the author while keeping the entire string.
Solution
#include<algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
int main () {
ifstream myfile;
vector<string> v;
myfile.open (\"file.txt\");
if (myfile.is_open())
{
string line;
while ( getline (myfile,line) )
{
v.push_back(line);
}
myfile.close();
}
else cout << \"Unable to open file\";
vector<string>q;
vector<string>j;
for (int i = 0; i < v.size(); i++){
string s=v[i];
string author1=s.substr(0, s.find(\"-\"));
string author2=s.substr(author1.length()+1,s.length()) ;
q.push_back(author2+\"- \"+author1);
}
sort(q.begin(),q.end());
for (int i = 0; i < q.size(); i++){
string s=q[i];
string author1=s.substr(0, s.find(\"-\"));
string author2=s.substr(author1.length()+1,s.length()) ;
j.push_back(author2+\"-\"+author1);
}
for(int i=0;i<j.size();i++){
cout <<j[i]<< \"\ \";
}
return 0;
}

