In: Computer Science
(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Ex:
Enter input string: Jill, Allen
(2) Print an error message if the input string does not contain a
comma. Continue to prompt until a valid string is entered.
Note: If the input contains a comma, then assume that the input
also contains two strings. (2 pts)
Ex:
Enter input string: Jill Allen Error: No comma in string. Enter input string: Jill, Allen
(3) Extract the two words from the input string and remove any
spaces. Store the strings in two separate variables and output the
strings. (2 pts)
Ex:
Enter input string: Jill, Allen First word: Jill Second word: Allen
(4) Using a loop, extend the program to handle multiple lines of
input. Continue until the user enters q to quit. (2 pts)
Ex:
Enter input string: Jill, Allen First word: Jill Second word: Allen Enter input string: Golden , Monkey First word: Golden Second word: Monkey Enter input string: Washington,DC First word: Washington Second word: DC Enter input string: q
_________________________
Given code to work with: main.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
/* Type your code here. */
return 0;
}
thanks.
SOLUTION-
I have solve the problem in C++ code with comments and screenshot
for easy understanding :)
CODE-
//c++ code
//header files
#include<iostream>
#include<string>
using namespace std;
//main
int main()
{
//declaration
string str, word1, word2;
//loop until input is true
while(true){
//ask for input
cout<<"Enter input
string:"<<endl;
getline(cin,
str); //get input
if(str=="q") //if user
type q then break and quit
break;
int pos = str.find(",");
//check for comma(,) in between words
if(pos==string::npos)
//if no comman found then print error
cout<<"Error: No comma in string."<<endl;
else{
word1 = str.substr(0, pos); //position for the first strings
word2 = str.substr(pos+1); //position for the Second
strings
int i=0;
while(word1[i]==' ')
word1 = word1.substr(1);
i=word1.size()-1;
while(word1[i]==' ')
word1 = word1.substr(0, i);
i=0;
while(word2[i]==' ')
word2 = word2.substr(1);
i=word2.size()-1;
while(word2[i]==' ')
word2 = word2.substr(0, i);
//print
cout<<"First word: "<<word1<<endl;
cout<<"Second word: "<<word2<<endl;
}
cout<<endl;
}
return 0;
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------