我的代码没有对字符串,C ++运行错误
my code doesn't run some thing wrong about strings, c++
我正在训练求解算法,我写了一个代码,但它不会编译在(如果)我无法检查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' )
相关文章:
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 将 opencv 从 2.4.13 转换为 3.3.1 时由 cv::resize() 引起的运行错误
- 为什么 leetcode 上有运行错误,而 vs2019 上没有错误?
- 我的代码没有对字符串,C ++运行错误
- C++运行错误:未分配正在释放的指针
- 代码块运行错误: "Process terminated with status -1073741510" 。我做错了什么?
- VS2013中SSE2代码的运行错误
- C++将文本文件读入数组,运行错误:分段错误
- c++运行错误
- 发生无法运行错误
- 简单C++程序在 Xcode、代码块和终端中运行错误
- C++入门练习 1.20 运行错误
- 使用 MinGW 和 netbeans 7.3.1 运行错误
- "snake"运行错误
- 处理提升端点侦听/运行错误
- 不运行错误LNK1120:1 个未解析的外部 VS
- 一切都是正确的,但不能运行:错误预期{或;
- 使用Qt Creator运行错误
- 在循环内输入字符串时出现运行错误
- 为什么sizeof在linux上运行良好,而在windows上遇到运行错误