subprogram to program

hi, who can convert this subprograms to a single main program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<iostream> 
using namespace std; 
  
// Function to print the sorted array of string 
void printArraystring(string,int); 
  
// Function to Sort the array of string 
// according to lengths. This function  
// implements Insertion Sort.  
void sort(string s[], int n) 
{ 
    for (int i=1 ;i<n; i++) 
    { 
        string temp = s[i]; 
  
        // Insert s[j] at its correct position 
        int j = i - 1; 
        while (j >= 0 && temp.length() < s[j].length()) 
        { 
            s[j+1] = s[j]; 
            j--; 
        } 
        s[j+1] = temp; 
    } 
} 
   
// Function to print the sorted array of string 
void printArraystring(string str[], int n) 
{ 
    for (int i=0; i<n; i++) 
        cout << str[i] << " "; 
} 
  

int main() 
{ 
    string arr[] = {"Computer", "I", "thru", "am"}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
      
    // Function to perform sorting 
    sort(arr, n); 
  
    // Calling the function to print result 
    printArraystring(arr, n); 
      
    return 0; 
}

and also cand you change the string arr[] = {"Computer", "I", "thru", "am"}; to be introduced fom the keyboard, please :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>

int main()
{
	std::vector<std::string> arr;

	for (std::string word; std::cout << "Enter word (CR to end): " && std::getline(std::cin, word) && !word.empty(); arr.push_back(word));

	std::sort(arr.begin(), arr.end());
	std::copy(arr.begin(), arr.end(), std::ostream_iterator<std::string>(std::cout, " "));
	std::cout << '\n';
}



or to enter words on one line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
#include <sstream>

int main()
{
	std::vector<std::string> arr;
	std::string line;

	std::cout << "Enter words: ";
	std::getline(std::cin, line);

	std::istringstream iss(line);
	for (std::string word; iss >> word; arr.push_back(word));

	std::sort(arr.begin(), arr.end());
	std::copy(arr.begin(), arr.end(), std::ostream_iterator<std::string>(std::cout, " "));
	std::cout << '\n';
}

Last edited on
What you have is a single program. The program contains 3 functions: sort, printArraystring, and main.

Shoving the code from sort and printArraystring into main can be done, but what you have here is a MUCH better way to go. I highly recommend that you keep the functions and not make is a single function.

As far as entering the strings from the keyboard, read up on I/O.

http://www.cplusplus.com/doc/tutorial/basic_io/

Read especially the sections "Standard input (cin)" and "cin and strings"
thanks @seeplus
Topic archived. No new replies allowed.