user7081818 user7081818 - 1 year ago 63
C Question

C- While loop not working

#include <stdio.h>
#include <string.h>

int main(void)
char str1[1000];
int i, letter, space = 0;
char ch = str1[i];

printf("Enter a sentence: ");
scanf("%[^\n]s", str1);
printf("you enter %s\n", str1);

while (i != strlen(str1)) {
if (ch != ' ') {
} else if (ch = ' ') {
printf("%d %d", letter, space);

loop isn't working and I can't seem to locate the problem. I am using the terminal in ubuntu and after printing the user string, I get a blank line. I have to use Ctrl-Z to stop the script.

Answer Source

Mistakes I see: using uninitialised variables - local variables do not get initialised automatically.

Another is you do not read a character from the string within the loop.

The third is the unecessary and syntactically incorrect if (ch=' ') which should have been if (ch==' ')


int main(void){
    char str1[1000];
    int i = 0, letter = 0, space = 0;       // initialise all to 0;

    printf("Enter a sentence: ");
    printf("you enter %s\n",str1);

    while (i!=strlen(str1)){
        char ch = str1[i];                  // move this inside the loop
        if (ch!= ' '){
        }else {                  // unnecessary - you already checked space
    printf("%d %d\n", letter, space);

Program session:

Enter a sentence: hallo my friend
you enter hallo my friend
13 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download