Question

Hi! 1. I need some help with sorting string in a text file. My goal is...

Hi!

1. I need some help with sorting string in a text file. My goal is to 1 shift left strings for string.length time. I was able to do that successfully. However, I am also trying to sort, using insertion sort , the resulting shifts. I store all shifts in a vector (or is it better to use an array?!) , and try to sort them that way, but my output is just the shifted strings but not sorted. Can anybody help with that? Also, let me know where I made a mistake.

2. Lastly, the sorted values should be written to a different file. When I try to do that, an ofstream file is created, but nothing is written to it.

____________________________________________________________________C++

LeftShift2.txt

Hi there!

---------------------------------------------------------------------------------------------------------------------

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <fstream>

using namespace std;

void shiftleft (string& s, int d)

{

reverse(s.begin(), s.begin() + d);

reverse(s.begin() + d, s.end());

reverse(s.begin(), s.end());

}

void insertionSort(vector<string> &arr)

{

int i, j;

string key;

for (i = 1; i < arr.size(); i++)

{

key = arr[i];

j = i - 1;

while (j >= 0 && arr[j] > key)

{

arr[j + 1] = arr[j];

j = j - 1;

}

arr[j + 1] = key;

}

}

void printArray(vector<string> array) {

for (int i = 0; i < array.size()-1; ++i)

cout << array[i] << endl;

}

int main(int argc, char *argv[])

{

string i;

string input_line;

vector<string> value;

cout << "encode" << endl;

getline(cin, i);

ifstream infile("LeftShift2.txt");

ofstream ofile("LeftShift3.txt");


if(infile.is_open() && i == "insertion")

{

while(getline(infile, input_line))

{

for(int i = 0; i < input_line.size(); i++)

{

cout << input_line << endl;

shiftleft (input_line, 1);

}

}

value.push_back(input_line);//push individual input_line into vector value

insertionSort(value);//lexicographically sort values in vector value.

printArray(value);//test to see if all element are sorted

ofile << infile.rdbuf();//copy sorted content of infile in ofile

}

}

-----------------------------------------------------------------------------------------------

LeftShift3.txt should be something like (notice how sorted lexicographically following ASCII table):

_there!Hi (_here is space)

!Hi there

e!Hi ther

so on and so forth

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution:

There were 3 problems:

1. inserting the shifted string in vector. You were doing it outside the while loop in main function. You are printing the value inside for loop, so the shifted string should be pushed just after calling the shiftleft function. value.push_back(input_line); statement should be inside for loop.

2. second problem in writing in output file using ofile. Like you have iterated through vector and printing it on screen in printArray function, the vector should be iterated and written elements one by one in file.

3. not closing the infile and ofile. you should call infile and ofile after use.

Program:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

void shiftleft(string& s, int d)
{
   reverse(s.begin(), s.begin() + d);
   reverse(s.begin() + d, s.end());
   reverse(s.begin(), s.end());
}

void insertionSort(vector<string> &arr)
{
   int i, j;
   string key;

   for (i = 1; i < arr.size(); i++)
   {
       key = arr[i];
       j = i - 1;

       while (j >= 0 && arr[j] > key)
       {
           arr[j + 1] = arr[j];
           j = j - 1;
       }

       arr[j + 1] = key;
   }
}

void printArray(vector<string> array) {
   for (int i = 0; i < array.size() - 1; ++i)
       cout << array[i] << endl;
}

int main(int argc, char *argv[])
{
   string i;
   string input_line;
   vector<string> value;

   cout << "encode" << endl;

   getline(cin, i);

   ifstream infile("LeftShift2.txt");
   ofstream ofile("LeftShift3.txt", ofstream::out);

   if (infile.is_open() && i == "insertion")
   {
       while (getline(infile, input_line))
       {
           for (int i = 0; i < input_line.size(); i++)
           {
               cout << input_line << endl;
               shiftleft(input_line, 1);

               value.push_back(input_line);//push individual input_line into vector value
           }
       }

       insertionSort(value);//lexicographically sort values in vector value.

       printArray(value);//test to see if all element are sorted

       //ofile << infile.rdbuf();//copy sorted content of infile in ofile

       ofile << "Hello" << endl;

       for (int i = 0; i < value.size() - 1; ++i)
           ofile << value[i].data() << endl;

       infile.close();
       ofile.close();
   }

   return 0;
}

Output:

encode insertion Hi there! i there!H there!Hi t he re!Hi he reHi t ereHi th re!Hi the e?Hi ther !Hi there the re!Hi Hi there

Output file content:

LeftShift3.txt - Notepad | File Edit Format View Help there! Hi !Hi there Hi there! e! Hi ther ere! Hi th here! Hi t i there!

Add a comment
Know the answer?
Add Answer to:
Hi! 1. I need some help with sorting string in a text file. My goal is...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hello, I need help with my code. The code needs to display random number from 1...

    Hello, I need help with my code. The code needs to display random number from 1 to 50 every time the program runs but the program displays the same random numbers every time. Thanks #include #include using namespace std; void dynAlloc(int size, int *&arr); void displayArray(int *arr, int n); void insertionSort(int *arr, int n, int *temp); void linear_search(int *arr, int n, int key); void binary_search(int *arr, int n, int key); int main() {   const int n = 50; int *arr,...

  • fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string>...

    fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct book { int ISBN; string Author; string Title; string publisher; int Quantity; double price; }; void choice1(book books[], int& size, int MAX_SIZE) { ifstream inFile; inFile.open("inventory.txt"); if (inFile.fail()) cout <<"file could not open"<<endl; string str;    while(inFile && size < MAX_SIZE) { getline(inFile, str); books[size].ISBN = atoi(str.c_str()); getline(inFile, books[size].Title);    getline(inFile, books[size].Author); getline(inFile, books[size].publisher);          getline(inFile,...

  • C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <...

    C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <iostream> #include <fstream> #include <string> using namespace std; int measureElementsPerLine(ifstream& inFile) {    // Add your code here.    string line;    getline(inFile, line);    int sp = 0;    for (int i = 0; i < line.size(); i++)    {        if (line[i] == ' ')            sp++;    }    sp++;    return sp; } int measureLines(ifstream& inFile) {    // Add your code here.    string line;    int n = 0;    while (!inFile.eof())    {        getline(inFile,...

  • In c++ please How do I get my printVector function to actually print the vector out?...

    In c++ please How do I get my printVector function to actually print the vector out? I was able to fill the vector with the text file of names, but I can't get it to print it out. Please help #include <iostream> #include <string> #include <fstream> #include <algorithm> #include <vector> using namespace std; void openifile(string filename, ifstream &ifile){    ifile.open(filename.c_str(), ios::in);    if (!ifile){ cerr<<"Error opening input file " << filename << "... Exiting Program."<<endl; exit(1); }    } void...

  • My code doesn't output correctly using a .txt file. How do I clean this up so...

    My code doesn't output correctly using a .txt file. How do I clean this up so it posts correctly? ----------------------------------------------- CODE ---------------------------------------------- #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <fstream> using namespace std; struct Customer {    int accountNumber;    string customerFullName;    string customerEmail;    double accountBalance; }; void sortDesc(Customer* customerArray, int size); void print(Customer customerArray[], int size); void print(Customer customerArray[], int size) {    cout << fixed << setprecision(2);    for (int i = 0; i...

  • I need help fixing my code: In C++ *************** 1) I want to sum the digits...

    I need help fixing my code: In C++ *************** 1) I want to sum the digits of an n*n matrix 2) find the average I have completed the rest ****Do not use C++ standard library. You must use pointers and pointer arithmetic to represent the matrix and to navigate through it. MY CODE: (I have indicated at which point I need help) #include <iostream> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp;...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I am having trouble trying to output my file Lab13.txt. It will say that everything is...

    I am having trouble trying to output my file Lab13.txt. It will say that everything is correct but won't output what is in the file. Please Help Write a program that will input data from the file Lab13.txt(downloadable file); a name, telephone number, and email address. Store the data in a simple local array to the main module, then sort the array by the names. You should have several functions that pass data by reference. Hint: make your array large...

  • can someone help me fix this. The function that finds the minimum and maximum values of...

    can someone help me fix this. The function that finds the minimum and maximum values of the array and outputs the value and index doesnt find the maximum value of the array. #include <iostream> #include <fstream> #include<iomanip> using namespace std; void readArray(ifstream& inF, int arr[], int&ArrSize); void writeArray(ofstream & outF, int arr[], int & ArrSize); void MaxAndMin(ofstream & outF, int arr[], int & ArrSize, int &high, int &low); int main() {    int arr[100];    int i = 0;   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT