arg c = 1 всегда независимо от того, сколько символов или слов в данном предложении - PullRequest
0 голосов
/ 09 июля 2020

Я хочу напечатать argc, чтобы убедиться, что слова вычисляются правильно, прежде чем перейти к следующему разделу в моем коде. Мой код:

int main(int argc, char *argv[])
{
    string s = get_string("Text:  ");
    //Read letters;
    n = strlen(s);

    printf("%d\n", n);
    printf("%d\n", argc);

Каждый раз, когда я запускаю программу, argc = 1 всегда, даже если набранное предложение содержит 4-5 слов. Я не уверен, почему программа неправильно вычисляет argc. Любая помощь приветствуется.

1 Ответ

0 голосов
/ 09 июля 2020

Итак, вы попросили прочитать текст из ввода и подсчитать количество букв и слов:


#include <stdio.h>
#include <ctype.h>

int main()
{
    char a[1000] = {0};
    
    //read a line from input
    scanf("%[^\n]s", a);
    
    int word_count = 0;
    int letter_count = 0;
    int idx = 0; 
    
    // go through the line
    while (a[idx]){
        
        //skip spaces
        while(a[idx] && isspace(a[idx]))
            idx++;
            
        // if next char is a letter => we found a word
        if (a[idx])
            word_count++;
        
        //skip the word, increment number of letters
        while (a[idx] && !isspace(a[idx])){
            letter_count++;
            idx++;
        }
    }
    
    printf("word count = %d letter count = %d", word_count, letter_count);
   
    return 0;
}

enter image description here


EDIT : display line count also


#include <stdio.h>
#include <ctype.h>

int main()
{
    char a[1000] = {0};
    
    //read everyting from input until character '0' is found
    scanf("%[^0]s", a);
    
    int word_count = 0;
    int letter_count = 0;
    int sent_count = 0;
    int idx = 0; 
    
    // go through the lines
    while (a[idx]){
       
        //skip spaces
        //newline is also a space, check and increment counter if found
        while(a[idx] && isspace(a[idx])){
            if (a[idx] == '\n')
                sent_count++;
            idx++;
        }
            
        // if next char is a letter => we found a word
        if (a[idx])
            word_count++;
        
        //skip the word, increment number of letters
        while (a[idx] && !isspace(a[idx])){
            letter_count++;
            idx++;
        }
    }
    
    printf("word count = %d letter count = %d line count = %d", word_count, letter_count, sent_count);
   
    return 0;
}

enter image description here

Here's another way:

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

int main()
{
    char a[1000] = {0};
    
    int word_count = 0;
    int letter_count = 0;
    
    while (1){
        scanf("%s", a);
        
        // break when word starts with '0'
        if (a[0] == '0')
            break;
            
        word_count++;
        letter_count += strlen(a);
    }
    
    printf("word count = %d letter count = %d", word_count, letter_count);
    
    return 0;
}

Этот способ считывает ввод до тех пор, пока не будет найдено слово, начинающееся с символа '0'

введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...