C++ 这个C代码有什么问题?我想知道输入字符串中1的数目
我想获得输入字符串中的1数(作为一个字符),但它不起作用。请告诉我原因C++ 这个C代码有什么问题?我想知道输入字符串中1的数目,c++,c,string,scanf,gets,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
#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;
}
#包括“stdio.h”
#包括“string.h”
int main()
{
int n,l,count1=0,i;
scanf(“%d”和“&n”);
字符a[n];
获得(a);
对于(i=0;i您的代码将跳过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;
}
#包括“stdio.h”
#包括“string.h”
#包括
int main()
{
int n,l,count1=0,i;
scanf(“%d”和“&n”);
字符a[n];
标准:cin>>a;
对于(i=0;i
是错误的,它的缓冲区太小,因为没有空间放置get()
将放在那里的终止符
不要这样做。事实上,不要对任何事情使用get()
相反,你应该这样做
char line[256];
if(fgets(line, sizeof line, stdin) != NULL)
{
printf("read a line, process here\n");
}
<>你用C++标注这个问题,在C++中有一个简单的方法来解决这个问题:
#include <algorithm> // for std::count
#include <iostream> // for std::cin and std::cout
#include <string> // for std::string
int main()
{
std::string s;
std::cin >> s; // reading in the string
auto n = std::count(s.cbegin(), s.cend(), '1'); // counting '1' characters
std::cout << "the number of '1's in the string \"" << s << "\" is: " << n << "\n";
}
#包括
如果您的编译器不支持C++11,则将auto
替换为std::size\t
它不考虑受保护的字符串('\0'
)的结尾字符
实际输入不是在scanf中输入的换行符,而是在get
中使用的
实际输入的字符数可能小于n
get
可能导致溢出。(它已过时)
老式的“C”:
int ch ;
int count = 0 ;
while ((ch = getchar()) != EOF)
{
if (ch == '1')
count += 1 ;
} ;
(未经测试)
使用<代码> STD::CIN < /C>和算法。这将变得更容易。是的,第一个问题是:你想在C或C++中这样做吗?@斯特凡,这是C。code@Hephaestos它被标记为c++
。更改为'scanf(“%d%*c”,&n);字符a[n+1]这是C代码,所以STD::CI::CUT和IOFSUM不可用。这是C代码,所以栈上的变量的定义只能在'{'之后立即可用,所以OP必须使用C++编译器。但是,它不是有效的C代码。问题用C++来标记。
int ch ;
int count = 0 ;
while ((ch = getchar()) != EOF)
{
if (ch == '1')
count += 1 ;
} ;