当前位置:网站首页>7-26 word length (input and output in the loop)

7-26 word length (input and output in the loop)

2022-07-01 08:07:00 Big fish

Your program reads a line of text , There are several words separated by spaces , With . end . You have to output the length of each word . The words here have nothing to do with language , It can include various symbols , such as it’s Count a word , The length is 4. Be careful , Consecutive spaces may appear in the line ; final . Don't count in .

Input format :
Input gives one line of text in one line , With . end

Tips : use scanf("%c",…); To read in a character , Until I read . until .

Output format :
Output the length of the word corresponding to this line of text in one line , Each length is separated by a space , There is no final space at the end of the line .

sample input :
It’s great to see you here.

sample output :
4 5 2 3 3 4

I've been stuck in the last test point , Very afflictive

Wrong code :

#include <stdio.h>
int main ()
{
    char ch;
    while(1)
    {
        int a=0;
        scanf("%c",&ch);
        while(ch!='\n'&&ch!=' '&&ch!='.') // When enter occurs , Space , This reading will end at the full stop 
        {
            a++;             // Count             
            scanf("%c",&ch); // Continue to enter the remaining letters of the word 
        }
        if(a!=0) // This word has a length 
        {
            printf("%d",a);
            if(ch!='.') printf(" "); // If there is a space at the end, one more space will be output , Replace the space here with * It can be seen that 
        }
        if(ch=='.') break; // After jumping out of the outermost loop , These are output together 
    }
    return 0;
}

Running results :
 stay
Then I asked the teacher , Find out : No, I didn 't . If a space is encountered before, a space will be output
Finally, it came out , The key is to add a counter count( In fact, it is only the first flag bit ).

Code :

#include <stdio.h>
int main ()
{
    char ch;
    int count=0;
    while(1)
    {
        int a=0;
        scanf("%c",&ch);
        while(ch!='\n'&&ch!=' '&&ch!='.')
        {
            a++;
            scanf("%c",&ch);
        }
        if(a!=0) 
        {
            count++; // Just for the first time 
            if(count==1) printf("%d",a); // Output the first number without a space in front of it 
            else printf(" %d",a); // When outputting the remaining numbers, there is a space in front ( Replace this space with * It can be seen clearly )
        }
        if(ch=='.') break;
    }
    return 0;
}

Ha ha ha ha ha ha ha ha ha !!!!!!

 Insert picture description here

原网站

版权声明
本文为[Big fish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160144552551.html