Home > Net >  How do you use switch statements in a for loop?
How do you use switch statements in a for loop?

Time:08-07

Recently, I've started learning C, and a project I'm doing rn is a program that converts any phrase into an ASCII title style artpiece. The way I want to do this is like a TV, scanning from top left to bottom right of the screen. To do this, I need to get a tally of all letters in that phrase. Right now I'm doing it with this snippit:

printf("Let's make your text an ASCII title!\n");
printf("Please input your phrase:");
scanf("%s", &phrase[20]);


for (i=0;i<=20;i  ) {
    switch (phrase[i]) {

        case 'A':
        aCounter  ;
        continue;

        case 'B':
        bCounter  ;
        continue;
        
    }
}

printf("A: %d", aCounter);
printf("B: %d", bCounter);

However, I've tried using the break; continue; and even leaving it empty, but it simply exits the for loop without any warning. Also, it doesn't return the correct number of (in this example) A, and B. How do I fix this?

CodePudding user response:

A continue; ignores switch statements when going up: it will use the innermost for or while.

A break; will use the innermost switch, for or while.

If neither break; nor continue; jump to where you want, you can use goto instead.

CodePudding user response:

'like a TV, scanning from left top left to ...', no, but this will return, the input, its ascii equiv and count. (I am just a learner, hope this is useful, if 'switch' answers are the only option pls, disregard)

char userInput[99];
int charCount = 0;
printf("please enter a phrase!\n");
fgets(userInput,99,stdin);

for(int i = 0; userInput[i] != '\0'; i   ){
    if(userInput[i]!='\0'){
            charCount  ;
        printf("%c\n",userInput[i]);   //returns user input up to the '\0' 
        printf("%d\n\n",userInput[i]); //also returns the ascii value of new line char (10)
        }
        }
        printf("CharCount was %d\n",charCount);
  • Related