In: Computer Science
Write a C++ function called parse that reads one line of user input from the keyboard and creates an array of the strings found in the input. Your function should be passed the array and a reference variable that is to be assigned the length of the array. Prompt the user and read the input from within the function.
For example: If the user inputs copy this that, the resulting array would have length 3 and contain the strings “copy”, “this”, and “that”.
Create a main function that has a loop that will continuously call the function until the user enters the string “quit”. After the function has returned control to main, print the contents of the array and its length.
Your program should:
Give detailed directions to the user.
Here is the complete code for the following problem. I have added all required comments in program as well as pre and post conditions for the method .
And also display the content of array at last to verify that out program is working fine.
Code:
#include <iostream>
#include <cstring>
using namespace std;
//pre-condition <-- an array of type string and and variable of
type int
//post-condition <-- an array with number of elements equal to
array length
//method to add a new string in array
void parse(string arr[], int& arr_len)
{
char c ;
int space_count = 0; //use to monitor if user gives more than one
space between words
//loop call the parse function untill user enter quit
//and read char by char from user
while(cin.get(c))
{
if( c != ' ') //if the next char is space
{
space_count = 0;
if(arr[arr_len] == "quit") //check if last entered string is space
and if yes then break loop
break;
arr[arr_len] += c; //otherwise add it into array untill get next
space
}
else if( c == ' ' && space_count ==0)
{
arr_len++;
space_count++;
}
}
}
int main()
{
//create two variable one for storing word in array
//and second count num of elements in array
string arr[40];
int arr_len = 0;
//call the parse method
parse(arr, arr_len);
//print the array to verify result
for(int i=0; i<arr_len; i++)
{
cout << arr[i] << " ";
}
return 0;
}
-----------------------------------------------------------------------------
Output: