gpt4 book ai didi

c++ - 无效转换、未指定行为和字符数组?

转载 作者:行者123 更新时间:2023-11-28 07:30:54 25 4
gpt4 key购买 nike

我正在尝试做 http://www.spoj.com/problems/SHLIGHTS/ ,为此我设计了一个解决方案。我是 C++ 的新手(大约 14 天),而且我面临很多问题。之前我用的是Python,没有出现过这些错误,反正我是这样写的..

#include <iostream>
#include <string>
#include <cstdio>
using namespace std;

//example is GBGBBB
//t=0, GBGBBB then t=1,BGBGBB then t=2 BBGBGB, then t=3 BBBGBG
//search for GB and replace it with BG

//we need a function that replaces things
string swapSEQ(string SEQ)
{
unsigned int sizeSEQ=SEQ.size();
unsigned int curr(0);
while (curr<sizeSEQ-1)
{
if (SEQ[curr]=="G" and SEQ[curr+1]=="B")
{
SEQ[curr]="B";SEQ[curr+1]="G";curr+=2;
}
else {++curr;}
}
return SEQ;
}

int main()
{
unsigned int numCases;
scanf("%d",&numCases);
// cin>>numCases;
for (unsigned int currentCase=0;currentCase<numCases;++currentCase)
{
string SEQ;
//scanf("%s",&SEQ);
cin>>SEQ;
string swapped=swapSEQ(SEQ);
unsigned long long t=0;
while (swapped!=SEQ)
{
swapped=swapSEQ(SEQ);++t;
}
printf("%lld\n",t);

}
return 0;
}

我知道有很多细节,但仅此而已。 SPOJ 在输入和输出后显示空行,但在阅读描述后,我明白我们必须在单行中做事。这是我使用 g++4.7 编译器 (LINUX) 得到的结果

SHLIGHTS.cpp: In function ‘std::string swapSEQ(std::string)’:
SHLIGHTS.cpp:17:18: error: comparison with string literal results in unspecified behaviour [-Werror=address]
SHLIGHTS.cpp:17:18: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
SHLIGHTS.cpp:17:37: error: comparison with string literal results in unspecified behaviour [-Werror=address]
SHLIGHTS.cpp:17:37: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
SHLIGHTS.cpp:17:52: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
SHLIGHTS.cpp:17:66: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
cc1plus: all warnings being treated as errors

*发生了什么事?有一些关于指针、const char 和未指定行为的东西。
**我知道指针是一种指向内存位置的变量,仅此而已。
**我在某些地方使用了 scanf 而在其他地方使用了 cin(如果我用 cin 替换 scanf,我会得到同样的错误)
**我返回的字符串作为参数是否与此有关?
**我在哪里使用了指针?
**我错了吗?C++ 中的字符串是字符数组吗?如果不是,那么无效转换在哪里?

提前致谢,如有任何不妥之处,我们深表歉意。如果太长,请回答任何疑问。

最佳答案

  1. 您需要将 SEQ[curr]'G' 而非 "G" 进行比较,因为它是一个字符而非字符串。
  2. 您应该使用运算符 && 而不是 and
  3. 你的逻辑有问题。在字符串的一个索引处,您只能有 1 个字符。所以写 if (SEQ[curr] == 'G' && SEQ[curr] == 'B' 和写 if (false) 是一样的。
  4. 这不是错误,但请不要滥用您的代码,在一行中编写多个命令。
  5. 如果您编写的是C++,请使用cin,而不是scanf
  6. 如果您从不使用它,为什么还要创建 sizeSEQ?不要!

关于c++ - 无效转换、未指定行为和字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17743838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com