c++ - 这段 C 代码有什么问题?我想知道输入字符串中 1 的个数

标签 c++ c string scanf gets

我想获取输入字符串中 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/

相关文章:

c++ - 带有 constexpr 函数失败的模板实例化

c++ - 在 c++ 中的不同行或列旁边搜索最小值和最大值的最快方法是什么

C:将整数值翻转为 bool 值

c++ - 为什么从字符串常量到 'char*' 的转换在 C 中有效但在 C++ 中无效

c++ - 将 char 数组转换为 WCHAR 数组的最简单方法是什么?

c++ - 应该重载 operator = 返回 class& 或 class

c++ - ISO C 中数组的左值到右值转换

c - 将值插入队列前端(链接列表)时发生写入访问冲突 (@ 0xCDCCDCD)

c# - 帮助在 C# 中包含字符串数组的哈希表

c++ - omn​​et : Simulation terminated with exit code: 139 中的导航层次结构错误