【问题标题】:Strlen error in cc中的Strlen错误
【发布时间】:2015-12-02 10:29:14
【问题描述】:
 #include <stdio.h>
#include <time.h>
#include <string.h>
char* matrix [10][10];  
int main(void){         
        int i;
          char* list[4];
         char words[20][20]={" c a t "," c a r "," b e a r "," s h i p "," m o u s e "," b e a t l e "," c o a t "," n e s t "," i c e "," s u g a r "," b a c o n "," f r o w n "," s m i l e "," d e a d "," f e a t h e r "," g o a t "," h e n "," j e l l y "," k o a l a "," l i p s "};

        int length=0;
        int num;
        int k;
        int m;
        char otherString=0;
        char c;
        int j;
        int s;
        int r;


        char test[10];
        char* token;

const char *search = " ";
        char* empty="";
        int size;
        int ans;

        int x;
        int y;
        int pos;
        int pos2;
        int randRow;
        int randColumn;
        int chosen[10];
        int random;
        int d;
        int ROWS      = 10;      // number of rows
 int COLUMNS   = 10;      // number of columns




        printf("\tA\tB\tC\tD\tE\tF\tG\tH\tI\tJ\n");


        srand(time(NULL));


            for(r=0;r<10;r++){

            for(s=0;s<10;s++){
srand(time(NULL));

            c='1';  


        memset(matrix,c,sizeof(matrix));        
            }}


        for( i=0;i<4;i++){
    printf( "\n%d",i );
    d=0;
        do{
            random = (rand()%20);
            list[i]=words[random];
            d=0;
            for( j=0;j<i;j++){
                if(strcmp(words[random],list[j])==0)d=1;
            }
        }while(d);


    printf("%s",words[random]);
    token = strtok((words[random]),search); 
    printf("%s",token);
    while(token!=NULL) 
   {
      printf("\nrand%d",random);
      length=strlen(words[(random)]);
     printf("len is:%d",length);
      matrix [i][0]=token;
          for( k=1;k<=length;k++){
          token = strtok(NULL, search); 
        printf("%s",token);

            matrix [i][k]=token;

      } 
    } }


            for(r=0;r<10;r++){
            printf("\n");   
            for(s=0;s<10;s++){




                 printf("\t%c",matrix[r][s]);


            }}


        getchar();
            return 0;
            }

因为字符是用空格分隔的,所以 strlen 将其余的标记为

垃圾。所以答案总是2。有什么想法可以解决吗?长度是 总是 2。 也许它假设空格意味着字符串的结尾?? 不知道怎么解决

【问题讨论】:

  • strlen 函数查找终止空字符 '\0',它不关心空格。
  • 您如何显示/使用length?您是否还显示所选单词以验证您是否在有效字符串上调用strlen?您是否包括string.h?了解更多上下文会有所帮助。
  • 您的结论不正确,您声称的结果没有意义。请提供Minimal Complete and Verifiable Example,以便我们可以准确查看您正在打印的内容并重现您的结果。
  • 您的代码格式/缩进...不寻常。
  • 为什么?我的代码有问题吗?

标签: c strlen


【解决方案1】:

除非您另有说明,否则 rand() 函数会自动播种值为 1。这就是为什么您每次都会得到相同的答案。

通过适当调用srand 进行修复,可能基于您的系统时钟时间。

strlen 不会丢弃空格,但会在到达第一个 \0 时返回。

【讨论】:

  • 即使每次使用相同的 rand() 值,我也看不到该数组中的任何元素会给出长度 2 ?
  • 除非 OP 打印的是 random 而不是 length。那将是我的猜测。但无法判断该问题当前的编写方式。
  • 我刚刚运行了一个快速测试,将 OPs 代码复制粘贴到一个空项目中,并输出长度和单词的值[随机]。它准确地给出了单词的长度,但正如这个答案正确指出的那样,由于播种,它总是会给出相同的答案。在我的例子中,random 的值为 2,它给出了答案“c a r”,长度为 7。支持这个答案
  • 我正在打印长度,
  • @chris 您可以编辑您的 OP 以显示您用于打印长度的代码吗?以及任何其他相关代码?由于rand 函数产生相同的值,您现在总是会得到相同的词。正如我的评论中所述,使用您的 OP 中的确切代码并添加 std::cout&lt;&lt;length&lt;&lt;std::endl; 每次都给了我 7,因为 rand() 总是会产生 1 而没有种子,这总是会选择 `c a r` 作为单词,并正确地告诉我它的长度。
【解决方案2】:

问题来了:

token = strtok((words[random]),search); 

strtok 通过用 0 终止符替换分隔符来修改其参数;第一次调用strtok 后," c a t " 变为" c",长度为2。

您需要对words[random]副本 执行strtok 调用,如下所示:

char temp[20];
strcpy( temp, words[random] );
...
token = strtok( temp, search );

编辑

不要过分苛刻,但是......你的代码是一个一团糟。我不确定您要完成什么,但是您有大量未使用的变量、几种类型不匹配、您的输出令人困惑且难以阅读等。糟糕的格式使代码难以理解和遵循;只是使缩进一致暴露了几个问题(例如多余的srand 调用)。 gcc 抛出了一堆关于未使用变量的警告,以及缺少 srandrand 的声明。

我已将您的代码缩减为专注于 strtokstrlen 问题,并重新格式化代码和输出以使其更具可读性。结果如下:

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

int main(void)
{
  int i;
  char words[20][20]={" c a t ",       " c a r ",     " b e a r ",   " s h i p ",   " m o u s e ",
                      " b e a t l e ", " c o a t ",   " n e s t ",   " i c e ",     " s u g a r ",
                      " b a c o n ",   " f r o w n ", " s m i l e ", " d e a d ",   " f e a t h e r ",
                      " g o a t ",     " h e n ",     " j e l l y ", " k o a l a ", " l i p s "};

  char* token;

  const char *search = " ";
  int random;

  srand(time(NULL));

  for( i=0;i<4;i++)
  {
    printf( "%d: ",i );
    random = rand() % 20;
    const char *blanks="                   ";
    printf("%.*s\"%s\", len is %2zu: token list:  ",(int) (strlen( blanks ) - (strlen(words[random]))),
                                                    blanks, words[random], strlen( words[random] ));
    char *sep = "";
    /**
     * strtok modifies the input string by overwriting the delimiter with
     * the 0 string terminator; to preserve the contents of words[random],
     * we need to copy it to a temporary string, and call strtok on that
     * copy.
     */
    char temp[20];                  
    strcpy( temp, words[random] );  
    token = strtok( temp, search ); 
    while(token!=NULL)              
    {
      printf("%s\"%s\"",sep, token);
      sep = ", ";
      token = strtok(NULL, search);
    }
    putchar( '\n' );
  }

  return 0;
}

这是输出:

0:             " c a r ", len is  7: token list:  "c", "a", "r"
1:       " b e a t l e ", len is 13: token list:  "b", "e", "a", "t", "l", "e"
2:           " b e a r ", len is  9: token list:  "b", "e", "a", "r"
3:             " c a t ", len is  7: token list:  "c", "a", "t"

我不知道你想用listmatrix 完成什么,但这至少应该有助于解决你在标记字符串时遇到的任何问题。

【讨论】:

  • strlen 每次仍然给出 2 :((
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多