I’m doing my school assignment and stuck in showing results.
#include <stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
/* Declare input variable */
char sentence[200]; // array that large enough for an sentence
int i;
/* Print the prompt */
printf("Enter a sentence:");
scanf("%s", &sentence);
/* Change all white space characters to a space */
for(i = 0; sentence[i]; i++)
{
if(isspace(sentence[i])) //isspace to convert space, \t, \n
sentence[i] = ' ';
}
/* Remove multiple spaces */
i = 0;
while(sentence[i] != '\0') // \0 = NULL byte -> 0x30, address
{
if(sentence[i] == ' ' && sentence[i+1] == ' ') // if there is two space
for(int j = i; sentence[j]; j++)
{
sentence[j] = sentence[j+1]; // eliminate one space
}
else
i++;
}
sentence[0] = toupper(sentence[0]); // Capitilize the first character of the sentence
for(i = 1; sentence[i]; i++)
{
sentence[i] = tolower(sentence[i]);
}
/* Display the Output */
printf("%s\n", sentence);
return 0;
}
I followed the direction, but the result shows like this:
enter image description here
I tried to build and run the code after annotating middle part to see if the input is same as output. But it came out the same as in the picture. I don’t think it’s a problem with the middle part, but I don’t know what the problem is.
>Solution :
You don’t need an ampersand here:
scanf("%s", &sentence);
In fact, you cannot get the whole sentence with the help of a scanf
function. You need functions like fgets
here. For example:
fgets(sentence, sizeof sentence, stdin);
and your problem is solved.
A sample output:
Enter a sentence:this sentence has a double space
This sentence has a double space