Could you show me how to code this kind of program? ----------------------------
ID: 3587810 • Letter: C
Question
Could you show me how to code this kind of program?
----------------------------------------------------------
You'll be sorting some strings. The first step will be to input a line from common input. As you do this, you should save each string into an array. Secondly, you'll sort the strings. I want you to do this in a specific way. Only sort each group of five consecutive strings, then move on to the next group, all the way until the end of the line. Lastly, print the groups of sorted strings on separate lines. I think an example will help to illustrate what I want here. First the input:
This is a sample sentence for the second assignment for CS 162.
And here is the desired output:
a is sample sentence This
assignment for for second the
162. CS
See how each line has five words which are sorted in alphabetical order? The first line has words 0-4, the second line has words 5-9, and the third line has words 10 and 11. Your program should do this no matter how long the input line is. As a final example, the input being:
This sentence is much longer than the first so that I can give you an example of something that basically goes on and on forever...
Gives the output:
is longer much sentence This
first so than that the
an can give I you
basically example of something that
and goes on on forever...
The only restriction on this project is that you cannot use predefined sort functions from the stl such as 'sort()' 'begin()' 'end()' etc.
Explanation / Answer
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string line;
string arr[5];
string word;
int count;
string temp;
cout << "Enter the line: ";
getline(cin,line);
istringstream iss(line);
count = 0;
while (iss >> word){
arr[count] = word;
if (count==4){
for (int i = 0; i <= count; i++){
for(int j= i; j<=count; j++){
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i<=count; i++)
cout << arr[i] << " ";
cout << endl;
count = 0;
}
else {
count++;
}
}
if (count > 0){
for (int i = 0; i < count; i++){
for(int j= i+1; j<count; j++){
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i<count; i++)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.