In c++ Given an input consisting of one or more sets of strings, followed by a f
ID: 3685514 • Letter: I
Question
In c++
Given an input consisting of one or more sets of strings, followed by a final line containing only the value 0. Each set starts with a line containing an integer, n, which is the number of strings in the set, followed by n strings, one per line.
Write a program that given the above input will output is a list of names in nondescending order by length (so that each name is at least as long as the one preceding it).
Example if you have the following input:
Input = { "7",
"Bo",
"Jean",
"Marybeth",
"Kevin",
"Claude",
"William",
"Pat",
"6",
"Jim",
"Ben",
"Annabelle",
"Zoe",
"Joey",
"Frederick",
"5",
"John",
"Billy",
"Fran",
"Stant",
"Cece",
"2",
"Jones",
"Bibi",
"0"
}
The output should looks like this:
Explanation / Answer
#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace std;
bool myfunction (string i,string j) { return (i.size()<j.size()); }
int main()
{
int i, j, n, m, k;
string Input[] = { "7",
"Bo",
"Jean",
"Marybeth",
"Kevin",
"Claude",
"William",
"Pat",
"6",
"Jim",
"Ben",
"Annabelle",
"Zoe",
"Joey",
"Frederick",
"5",
"John",
"Billy",
"Fran",
"Stant",
"Cece",
"2",
"Jones",
"Bibi",
"0" };
string temp[100];
n = sizeof(Input)/sizeof(Input[0]);
for(i=0;i<n;)
{
m = atoi(Input[i].c_str());
cout<<m<<endl;
if(m==0)
break;
for(j=0, ++i ; j<m; j++, i++) //to copy every intermediate chunk of strings
temp[j] = Input[i];
sort(temp, temp+m,myfunction); //sort according to the output of "myfunction"
for(k=0;k<m;k++)
cout<<temp[k]<<endl;
}
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.