Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中的If循环未正确迭代_C - Fatal编程技术网

C中的If循环未正确迭代

C中的If循环未正确迭代,c,C,在C上写一个单词计数器。我正在计算字符串中的空格数以确定单词数。我猜我的if语句有问题。有时它会计算字数,有时它会抛出随机数?例如,“我的红狗”有三个词,但“我喝朗姆酒”有一个词,“这个代码没有意义”有三个词。它正在打印每个字符串的长度 下面是有问题的代码部分: void WordCounter(char string[]) { int counter = 1; int i = 0; int length = strlen(string); printf("\nTh

在C上写一个单词计数器。我正在计算字符串中的空格数以确定单词数。我猜我的if语句有问题。有时它会计算字数,有时它会抛出随机数?例如,“我的红狗”有三个词,但“我喝朗姆酒”有一个词,“这个代码没有意义”有三个词。它正在打印每个字符串的长度

下面是有问题的代码部分:

void WordCounter(char string[])
{   int counter = 1; 
    int i = 0;
    int length = strlen(string);
    printf("\nThe length of your string is %d", length);

    for( i=0;i<length;i++){

        if (string[i] == ' ')
        {
            counter+=1;
            ++i;

        }
        else

        {
            counter +=0;
            ++i;
        }
    }

    printf("There are %d words in this sentence and i is equal to: %d", counter, i);
}
void字计数器(字符字符串[])
{int计数器=1;
int i=0;
int length=strlen(字符串);
printf(“\n字符串的长度为%d”,长度);

for(i=0;ifor循环的i++部分意味着i在每个循环中递增,您不应该在循环中再次递增。此外,此处不需要使用else。您需要删除位以获得:

for( i=0;i<length;i++) {
    if (string[i] == ' ')
    {
        counter+=1;
    }
}

for(i=0;i您的代码在3个不同的位置有增量i。增量只需要循环。
请尝试以下代码:

for( i=0;i<length;i++){
    if (string[i] == ' ')
    {
        counter++;
    }
}

for(i=0;i您在同一循环中递增i 2次。一次在for语句中,一次在循环中。这意味着您只在两个字符上检查一个字符。这可以解释为什么所有对空格都不在计数中:

我输入了所有成对字符:

myreddog”:两个空格都是未配对的数字

IdrInkrum”:两个空格都是未配对的数字

以下是您更正的源代码:

void WordCounter(char string[]){   
int counter = 1; 
int i = 0;
int length = strlen(string);
printf("\nThe length of your string is %d", length);

for( i=0;i<length;i++){

    if (string[i] == ' ')
    {
        counter+=1;
    }
}

printf("There are %d words in this sentence and i is equal to: %d", counter, i);
}
void字计数器(字符字符串[]){
int计数器=1;
int i=0;
int length=strlen(字符串);
printf(“\n字符串的长度为%d”,长度);

对于(i=0;i您甚至不需要i变量

counter = 0;
while(*str) 
    counter += *str++ == ' ' ? 1 : 0;
printf("There are %d spaces (not words as you may have more              spaces between words) in this sentence and length of the string is: %d", counter, length);



int isDelimeter(int ch, const char *delimiters)
{
    return strchr(delimiters, ch) != NULL;
}

const char *skipDelimiters(const char *str, char *delimiters)
{
    while (*str && isDelimeter(*str, delimiters)) str++;
    return str;
}

const char *skipWord(const char *str, char *delimiters)
{
    while (*str && !isDelimeter(*str, delimiters)) str++;
    return str;
}

const char *getWord(const char *str, char *buff, char *delimiters)
{
    while (*str && !isDelimeter(*str, delimiters)) *buff++ = *str++;
    *buff = 0;
    return str;
}

int countWords(const char *str, char *delimiters)
{
    int count = 0;
    while (*str)
    {
        str = skipDelimiters(str, delimiters);
        if (*str) count++;
        str = skipWord(str, delimiters);
    }
    return count;
}

int printWords(const char *str, char *delimiters)
{
    char word[MAXWORDLENGTH];
    int count = 0;
    while (*str)
    {
        str = skipDelimiters(str, delimiters);
        if (*str)
        {
            count++;
            str = getWord(str, word, delimiters);
            printf("%d%s word is %s\n", count, count == 1 ? "st" : count == 2 ? "nd" : count == 3 ? "rd" : "th", word); 
        }
    }
    return count;
}

您发布的代码最大的问题是,它错误地增加了
i
,而不应该增加

for( i=0;i<length;i++){

    if (string[i] == ' ')
    {
        counter+=1;
        ++i; // here

    }
    else
    {
        counter +=0;
        ++i; // here
    }
}
每当你索引一个空格
'
字符时,这个计数器就会递增。对于一个简单的算法,这可能就足够你所尝试的了


计算空格,而不是单词

您的算法实际上不计算字数,它只计算遇到的空格字符数,再加上一个。这意味着某些输入,例如下面的输入(用于记录字符串中的内容的引号,实际上不存在),将不会返回准确的字数:

// shoud be zero, but returns one
"" 

// should be zero, but returns four (three spaces)
"   "

// should be one, but returns five (two spaces, either side)
"  word  "

// should be two, but returns three (two spaces between)
"word  word"

etc.  
需要一个更健壮的算法。请注意,这并不能解决所有问题,但它使您更接近于计算我们所称的“单词”。也就是说,由空格字符分隔的非空格字符,可能会一直到字符串的末尾

这使用的是指针而不是索引。在我看来,它更容易阅读,并将代码从索引语法中分离出来,从而放大了实际情况:使用空白,然后使用我们称为“单词”的非空白。内联注释应该解释发生了什么:

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

int WordCounter(const char *s)
{
    int counter = 0;

    // while we haven't reached terminating nullchar
    while (*s)
    {
        // discard all whitespace until nullchar or non-whitespace found
        for (; *s && isspace((unsigned char)*s); ++s);

        // if not nullchar, we have the start of a "word"
        if (*s)
        {
            ++counter;

            // discard all text until next whitespace or nullchar
            for (; *s && !isspace((unsigned char)*s); ++s);
        }
    }

    return counter;
}

int main()
{
    const char *s1 = "There should be eight words in this string";
    printf("\"%s\"\nwords: %d\n", s1, WordCounter(s1));


    const char *s2 = "  There   should\t\t\tbe  eight\n in\n this\n string too\n ";
    printf("\"%s\"\nwords: %d\n", s2, WordCounter(s2));

    const char *s3 = "One";
    printf("\"%s\"\nwords: %d\n", s3, WordCounter(s3));

    const char *s4 = "";
    printf("\"%s\"\nwords: %d\n", s4, WordCounter(s4));

    return 0;
}
不完美;只是更好


先前的算法仍然不完美。要准确提取单个单词,需要掌握标点符号、可能的连字号等知识。但它离目标似乎要近得多。希望你能从中有所收获。

为什么要在三个不同的位置增加
i
?那些
++i
不属于你的在循环体中;for循环的增量步骤中的一个就足够了。不相关的,
count+=0;
听起来一文不值。它完全没有意义。删除if块中的
++i
并完全删除整个else块可能会让您接近您要查找的内容。请注意,您的算法非常复杂严格的。它假设只有空格分隔单词,并且每个分隔只有一个空格。解决一个更健壮的算法以容纳多个空格字符、并发空格字符、忽略尾随空格字符等,需要相当多的代码,但我怀疑您的初始任务是煮沸大海。从t开始他是基础。需要一本好的C语言书。研究循环然后开始编写程序
如果
-
循环
什么?有什么解释吗?请不要即兴。注意
int counter=1;
@Weather Vane我的意图是通过计算空格来表明,他不计算单词。这只是@WhozCraig.介绍的一条评论简单的指针式解决方案和巧妙的三元运算符不太可能有助于操作…,也不能解决多个空格的问题。@Weather Vane,特别适合您的要求
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int WordCounter(const char *s)
{
    int counter = 0;

    // while we haven't reached terminating nullchar
    while (*s)
    {
        // discard all whitespace until nullchar or non-whitespace found
        for (; *s && isspace((unsigned char)*s); ++s);

        // if not nullchar, we have the start of a "word"
        if (*s)
        {
            ++counter;

            // discard all text until next whitespace or nullchar
            for (; *s && !isspace((unsigned char)*s); ++s);
        }
    }

    return counter;
}

int main()
{
    const char *s1 = "There should be eight words in this string";
    printf("\"%s\"\nwords: %d\n", s1, WordCounter(s1));


    const char *s2 = "  There   should\t\t\tbe  eight\n in\n this\n string too\n ";
    printf("\"%s\"\nwords: %d\n", s2, WordCounter(s2));

    const char *s3 = "One";
    printf("\"%s\"\nwords: %d\n", s3, WordCounter(s3));

    const char *s4 = "";
    printf("\"%s\"\nwords: %d\n", s4, WordCounter(s4));

    return 0;
}
"There should be eight words in this string"
words: 8
"  There   should           be  eight
 in
 this
 string too
 "
words: 8
"One"
words: 1
""
words: 0