我是初学者,欢迎替代此代码。 输入值后程序崩溃。 我也想更多地了解这个问题,因为我已经看过很多次了。
#include<cstdio>
#include<vector>
#include<iostream>
#include<string>
using namespace std;
int main()
{
vector<string> str;
int n,i=0,count=0,a=0,b=1;
string j;
cin >> n;
while(i<n)
{
cin >> j;
str.push_back(j);
i++;
}
for(i=0;i<n;i++)
{
while(b!='\0')
{
if(str[i][a] == str[i][b])
{
count++;
}
a++;
b++;
}
}
cout << count;
return 0;
}
最佳答案
为了让你的奇怪程序运行,你应该做三件事:
在每个外部循环步骤中将初始值设置为 a
和 b
;
将 b!='\0'
条件更改为 str[i].c_str()[b]!='\0'
以检查不是 b
,但字符串文字;
在您的字符串上调用 string::c_str()
方法,因为不能保证字符串将以 null 终止,只有 c 风格的字符串符合这种情况。
for(i=0;i<n;i++)
{
a = 0;
b = 1;
while(str[i].c_str()[b]!='\0')
{
if(str[i].c_str()[a] == str[i].c_str()[b])
{
count++;
}
a++;
b++;
}
}
关于c++ - 另类角色 - HackerRank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498762/