argc = 1 始终不管给定句子中有多少个字符或单词

argc = 1 always regardless of how many characters or words in a given sentence

我想打印 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。非常感谢任何帮助。

因此您要求从输入中读取文本并计算字母和字数:


#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;
}


编辑:也显示行数


#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;
}

这是另一种方式:

#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”开头的单词