In C please. not C+. Currently running into some errors and seem to get the prog
ID: 3800176 • Letter: I
Question
In C please. not C+. Currently running into some errors and seem to get the program to fully work
1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Examples of strings that can be accepted:
Jill, Allen
Jill , Allen
Jill,Allen
Ex:
(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:
(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:
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)
Ex:
My code and current errors are below
#include<stdio.h>
#include <string.h>
int main(void) {
while(1){
char string[100];
int i = 0;
char x[100];
char y[100];
while(i<100) {
string[i] = '';
x[i] = '';
y[i] = '';
i++;
}
printf("Enter input string: ");
fgets(string, 100, stdin);
i = 0;
int f = 1;
while(i<100) {
if(string[i] == ','){
f = 0;
int j = 0;
i++;
while(string[i] != '') {
y[j] = string[i];
i++;
j++;
}
printf("First word: %s ", x);
printf("Second Word: %s ", y);
break;
}
else {
x[i] = string[i];
}
i++;
}
if(f == 1){
printf("Error: No comma in string. ");
return 0;
}
}
return 0;
}
My current errors
2. Compare output Jill Allen Jill Allen Input Jill Allen Enter input string Your output starts with Error: No comma in string Enter input string: Error No comma in string Enter input string Error No comma in string Expected output starts with J Enter input string Error No comma in string Enter input string 3. Compare output Jill Allen nput Enter input string Your output starts with First word: Jill Second Word Allen Enter input string: Expected output starts with First word: Jill Second word Allen 0/2 0/2Explanation / Answer
I have corrected your code. Please feel free to ask any doubt.
Please give the thumbs up to my solution.
#include<stdio.h>
#include <string.h>
void removeSpaces(char *string)
{
int i;
int count = 0;
for (i = 0; string[i]; i++){
if (string[i] != ' ')
string[count++] = string[i];
}
string[count] = '';
}
int main(void) {
while(1){
char string[100];
int i = 0;
char x[100];
char y[100];
while(i<100) {
string[i] = '';
x[i] = '';
y[i] = '';
i++;
}
printf("Enter input string: ");
fgets(string, 100, stdin);
removeSpaces(string);
i = 0;
int f = 1;
if(string[i]=='q'){
break;
}
while(i<100) {
if(string[i] == ','){
f = 0;
int j = 0;
i++;
while(string[i] != '') {
y[j] = string[i];
i++;
j++;
}
printf("First word: %s ", x);
printf("Second Word: %s ", y);
break;
}
else {
x[i] = string[i];
}
i++;
}
if(f == 1){
printf(" Error: No comma in string. ");
}
}
return 0;
}