c - Even after incrementing the value of the variable it won't change in the while loop
问题描述
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main()
{
char s[] = "We promptly judged antique ivory buckles for the next prize";
for(int i=0;i<strlen(s);i++)
{
s[i] = tolower(s[i]);
}
int i=0;
int n=1;
int counter =0;
char *s1;
s1=(char*)malloc(sizeof(char)*n);
s1[0] = s[0];
int k=0;
while(s[i]!='\0')
{
for( k=0;k<strlen(s1);++k)
{
if(s[i] == s1[k] && s[i] !=' ')
++counter;
}
if(counter==0 && s[i]!=' ' )
{
++n;
s1 = realloc(s1, sizeof(char) * (n));
++k;
printf("%d : %d\n",n,k);
s1[k] = s[i];
}
++i;
counter =0;
k=0;
}
s1 =realloc(s1 , sizeof(char)*(n+1));
s1[n] = '\0';
printf("%s\n",s1);
if(n == 26)
printf("yes");
else
printf("No");
return 0;
}
This program seeks to check whether the word is pangram or not.. It takes a letter from the array s and stores it in array s1 if the letter is not repeated in the latter. Thus if the length of the array s1 after the while loop finishes is 26 it has all the letters possible. But when i tried printing the s1 array it shows only w has its contents.. Confused to the extreme...
解决方案
不需要您的++k
(在if
语句中),将其删除,它将起作用:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main()
{
char s[] = "We promptly judged antique ivory buckles for the next prize";
for(int i=0;i<strlen(s);i++)
{
s[i] = tolower(s[i]);
}
int i=0;
int n=2;
int counter =0;
char *s1;
s1=(char*)malloc(sizeof(char)*n);
s1[0] = s[0];
s1[1]='\0';
int k=0;
while(s[i]!='\0')
{
for( k=0;k<strlen(s1);++k)
{
if(s[i] == s1[k] && s[i] !=' ')
++counter;
}
if(counter==0 && s[i]!=' ' )
{
++n;
s1 = realloc(s1, sizeof(char) * (n));
/* ++k; */ /* <== REMOVE IT */
printf("%d : %d\n",n,k);
s1[k] = s[i];
s1[k+1]='\0';
}
++i;
counter =0;
k=0;
}
s1 =realloc(s1 , sizeof(char)*(n+1));
s1[n] = '\0';
printf("%s\n",s1);
if(n == 26)
printf("yes");
else
printf("No");
return 0;
}
k
for
在语句末尾已经增加,因此++k
后者是导致错误结果的原因。也s1
应该初始化为NULL
终止,并且应该在语句NULL
内部保持终止,因为它可能包含垃圾。if
s1
推荐阅读
- visual-studio - 无法登录 Visual Studio 2017
- php - 如何保持 php://stdout 永远打开
- mysql - 无法连接到Mysql服务器,没有设置root密码
- elasticsearch - 从索引/存储中过滤 Elasticsearch 字段
- android - 在 Recycler 视图项之间添加图像
- authorization - 使用社交身份验证限制访问静态网站的最简单方法是什么
- laravel - Laravel - 选择/加入朋友到帖子表
- git - Sourcetree 中的“修改最新提交”,创建不相关的错误
- c# - 如何编写 RedirectToAction 的扩展方法以在 Mvc 中设置 TempData?
- android - 后台线程中的位图操作使 UI 无响应