我想获取输入字符串中 1(作为字符)的数量,但它不起作用。请告诉我原因。
#include"stdio.h"
#include"string.h"
int main()
{
int n,l,count1=0,i;
scanf("%d",&n);
char a[n];
gets(a);
for(i=0;i<n;i++)
{
if(a[i]=='1')
count1++;
}
printf("%d",count1);
puts(a);
return 0;
}
最佳答案
由于您之前输入的换行符,您的代码将跳过 gets() ,换行符是 gets() 的分隔符。虽然在 scanf 之后立即使用 getchar() 应该可以工作,但我建议使用这个
#include"stdio.h"
#include"string.h"
#include <iostream>
int main()
{
int n,l,count1=0,i;
scanf("%d",&n);
char a[n];
std::cin>>a;
for(i=0;i<n;i++)
{
if(a[i]=='1')
count1++;
}
printf("%d",count1);
std::cout<<a;
return 0;
}
关于c++ - 这段 C 代码有什么问题?我想知道输入字符串中 1 的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24694435/