我正在接受有关解算算法的培训,我写了一段代码,但不会编译
in(if)我无法检查s[i]=='S'
。
我正在尝试s[i]
是不是S字符,但我不知道我的问题在哪里。
如果我不能使用这种语法,可能有什么解决方案?
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w=25,v_s=25,d_w=25,d_s=25;
int n;
cin>>n;
string s[]={"WSSS"};
int i ;
for (i=0; i<n; i++)
{
if( s[i] == "W" )
{
v_s += 50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"1 \n";
}
if(s[i]=='W')
{
v_w +=50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"2 \n";
}
return 0;
}
cout<< d_w<<endl<<d_s;
}
答案 0 :(得分:4)
string s[]={"WSSS"};
表示string
的数组,其中第一个是"WSSS"
。
您需要的是:
std::string s="WSSS";
答案 1 :(得分:2)
string s[] = {"Hello"}
是一个字符串数组(好吧,一个字符串)。
如果你迭代它,或索引它s[0]
是“你好”。
然而
string s{"Hello"}
是一个字符串,由字符组成。
如果你对它进行迭代,或者将其编入索引s[0]
,你就会得到'H'。
为了预先排除字符串与字符问题排序时出现的所有其他问题,让我们从for循环的中间移动return 0;
。
然后让我们考虑如果输入的数字n
大于字符串的长度会发生什么:
int n;
cin>>n; //<- no reason to assume this will be s.length (0 or less) or even positive
string s{"WSSS"}; //one string is probably enough
int i ;
for(i=0;i<n;i++)
{
if( s[i] == 'W' ) //ARGGGGGGG may have gone beyond the end of s
{
事实上,让我们暂时放弃它,稍后再回过头来。让我们使用一个基于循环的范围......
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w = 25, v_s = 25, d_w = 25, d_s = 25;
string s{ "WSSS" };
for (auto && c : s)
{
if (c == 'W')
{
v_w += 50;
d_w = d_w + (v_w / 2);
d_s = d_s + (v_s / 2);
cout << "2 \n";
}
}
cout << d_w << '\n' << d_s << '\n'; //<- removed endl just because...
return 0;
}
答案 2 :(得分:0)
s是一个字符串数组,在这种情况下它只有元素:
string s[] = {"WSSS"};
所以写s[2];
//是未定义的行为
如果用户输入的n
大于s
中的元素数量,则代码将生成UB:
n = 4;
for(i = 0; i < n; i++) // s[3] will be used which causes UB
{
if( s[i] == 'W' ) // s[i] is a string not just a single char
{
}
}
只要s是一个字符串数组,然后检查它的元素,将它们检查为字符串而不仅仅是单个字符:
if( s[i] == "W" ) // not if( s[i] == 'W' )
我想你想要一个字符串:
string s = {"WSSS"};
因为您可能习惯于将下标运算符添加到字符串中:
char s[] = {"WSSS"};
如果是,那么上述条件是正确的:
if( s[i] == 'W' )