我的代码没有对字符串,C ++运行错误

my code doesn't run some thing wrong about strings, c++

本文关键字:运行 错误 字符串 代码 我的      更新时间:2023-10-16

我正在训练求解算法,我写了一个代码,但它不会编译在(如果)我无法检查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;
}

string s[]={"WSSS"};表示一个string数组,第一个是"WSSS"

您需要的是:

std::string s="WSSS";

string s[] = {"Hello"}是一个字符串数组(嗯,一个字符串)。

如果你迭代它,或者索引到它s[0]是"你好"。

string s{"Hello"}是一个字符串,由字符组成。

如果你迭代它,或者索引到它s[0],你会得到'H'。


为了抢占在对字符串与字符问题进行排序时会出错的所有其他事情,让我们将return 0;从 for 循环的中间移开。

然后让我们考虑一下如果输入的数字大于字符串的长度会发生什么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
    {

事实上,让我们暂时放弃它,稍后再回来。让我们使用基于范围 for 循环...

#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;
}

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' )