Hi how are you guys? I just wanted to ask a favor if you could find the syntax error and tell me what I am doing wrong. My prof. just taught the class about Vectors and she wanted us to modify an array program into a vector.
The array program I made includes a sort function that sorts an array of strings in alphabetical order.
And this is my version of trying to do it in a vector:
The array program I made includes a sort function that sorts an array of strings in alphabetical order.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void sort(string cookie[], int n);
void print(string cookie[], int n);
int main()
{
int rows=0;
char filename[30];
string names[100];
ifstream alphabet;
alphabet.open ("letters.txt");
if (alphabet.fail())
{
cerr << "Error opening input file." << endl;
exit(1);
}
while (getline(alphabet,names[rows]))
{
rows++;
}
sort(names,rows);
print(names,rows);
alphabet.close();
return 0;
}
void sort(string cookie[], int n)
{
int i, j;
string temp;
for(i=1; i<n; i++)
{
temp = cookie[i];
for(j=i; j>=1 && (temp < cookie[j-1]); j--)
{
cookie[j] = cookie[j-1];
cookie[j-1] = temp;
}
}
}
void print(string cookie[], int n)
{
for(int i=0; i<n; i++)
{
cout << cookie[i] << endl;
}
}
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void sort(string cookie, int n);
void print(string cookie, int n);
vector<char>filename;
vector<char>names;
int main()
{
int rows=0;
string cookie;
ifstream alphabet;
alphabet.open ("letters.txt");
if (alphabet.fail())
{
cerr << "Error opening input file." << endl;
exit(1);
}
while (getline(alphabet,names[rows]))
{
rows++;
}
sort(cookie,rows);
print(cookie,rows);
alphabet.close();
return 0;
}
void sort(string cookie, int n)
{
unsigned int i, j;
unsigned char temp;
unsigned int cookiesize = cookie.size()-1;
for(i = 0; i <= cookiesize; i++)
{
names.push_back(cookie[i]);
}
for(i=1; i<names.size()-1; i++)
{
unsigned int totalsize = names.size()-1;
temp = cookie[i];
for(j=i; (j>=1 && temp < cookie[j-1]); j--)
{
cookie[j] = cookie[j-1];
cookie[j-1] = temp;
}
}
}
void print(string cookie[], int n)
{
for(int i=0; i<n; i++)
{
cout << cookie[i] << endl;
}
}
Comment