Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have to code multiple problems in Code Blocks. I understand how to get the cod

ID: 3814224 • Letter: I

Question

I have to code multiple problems in Code Blocks. I understand how to get the code, but when I put it all together, it only looks at the first string over the one it's supposed to use.

#include <stdlib.h>

int main(void)
{
printf("Problem #1: ");
char string [45];
int i;
int count=0;
printf("Enter a string without spaces: ");
scanf("%s", &string);
for(i=0; string[i]!='';i++){
count++;
}
printf("That word has %d characters ",count);


printf("Problem #2: ");
char input[100];
int ch=0;
int space = 0;
int j;
printf("Enter a string with spaces: ");
scanf("%s",&input);
for(j=0; input[j]!=''; j++){
if(input[j]==' ')
{
ch++;
while(input[j]==' ')
{
j++;
}

}
space++;
}
fgets(input,j,stdin);
printf("That string has %d spaces and %d that aren't spaces ",ch,space);

For the first problem, I just need to count the number of characters in the word that the user types in, and in the second, I need to count the number of spaces and characters in a phrase. They work separately, but when I put them together, the second problem uses the first word typed in over the phrase that is typed in for the second problem. So my question is, how do I fix this?

Explanation / Answer

Below is the correct code. The mistakes in your code were:
1. scanf("%s", st) scans a string st till it finds a space or a new line. To ignore spaces and scan a string till end of line, use 'scanf("%[^ ]", string)'. This signifies that the string needs to be scanned till the characters inside the square brackets i.e. EOL(End of Line) is reached.

2. Use a getchar() before scanning for the second problem. After the first EOL character is encountered, it is not scanned and the first scan ends before it. So, for the second scan, it encounters the first EOL character as its first character. So, it needs to be scanned separately so that the 2nd problem's scanf doesn't encounter that EOL.

The code:

#include <bits/stdc++.h>
int main(void)
{
printf("Problem #1: ");
char string [45];
int i;
int count=0;
printf("Enter a string without spaces: ");
scanf("%[^ ]", string);
for(i=0; string[i]!='';i++){
count++;
}
printf("That word has %d characters ",count);
getchar();
printf("Problem #2: ");
char input[100];
int ch=0;
int space = 0;
int j;
printf("Enter a string with spaces: ");
scanf("%[^ ]",input);
for(j=0; input[j]!=''; j++){
if(input[j]==' ')
{
ch++;
while(input[j]==' ')
{
j++;
}
}
space++;
}
fgets(input,j,stdin);
printf("That string has %d spaces and %d that aren't spaces ",ch,space);
return 0;
}

Feel free to comment if you have any more doubts. I'll be happy to help