In: Computer Science
In C Please
*Asked before but all previous answers do not work correctly*
10.6 LAB: Warm up: Parsing strings
(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Ex:
Enter input string: Jill, Allen |
(2) Report an error 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 |
Code
#include <stdio.h>
#include<string.h>
int checkComma(char []);
#define MAX_SIZE 50
int main() {
char str[MAX_SIZE];
char firstWord[MAX_SIZE/2];
char secondWord[MAX_SIZE/2];
int commaPos,i,j;
while(true)
{
printf("Enter input string:\n");
scanf("%[^\n]%*c", str);
if(strcmp(str, "q")==0)
break;
commaPos=checkComma(str);
if(commaPos>0)
{
j=0;
for(i=0;i<commaPos;i++)
{
If(str[i]!=' ')
firstWord[j]=str[i];
j++;
}
firstWord[i]='\0';
j=0;
for(i=commaPos+1;i<str[i]!='\0';i++)
if(str[i]!=' ')
{
secondWord[j]=str[i];
j++;
}
secondWord[j]='\0';
printf("First word: %s\n",firstWord);
printf("Second word: %s\n",secondWord);
}
else
{
printf("Error: No comma in string.\n");
}
}
}
int checkComma(char str[])
{
int i=0;
for(i=0;str[i]!='\0';i++)
if(str[i]==',')
return i;
return -1;
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.