C++(SPOJ-POL polowa)-编译问题



我在SPOJ中为该任务生成正确的代码时遇到问题https://pl.spoj.com/problems/POL/.当我写下所有我需要的东西时,程序运行正常。但当我试图将其转换为函数时,我在ideone.com上遇到了这样的问题->双重免费或损坏(out(。有人能帮我吗?我做错了什么?我是初学者,我意识到这可能很琐碎。

#include <iostream>
using namespace std;
int polowa()
{
int t;
cin>>t;
string slowa[100]={};
string nowe_slowa[100]={};
for (int i=0;i<t;i++)
{
cin>>slowa[i];
}
for (int i=0;i<t;i++)
{
int k=slowa[i].length()/2;
nowe_slowa[i]=slowa[i].substr(0,k);
cout<<nowe_slowa[i]<<endl;
}
}
int main()
{
polowa();
return 0;
}

int polowa()承诺返回int,但函数中明显没有return关键字。

仔细查看代码,您永远不会一次使用多个元素。很有可能你可以重写这个函数,不使用数组,只使用一个循环user4581301

您不必将读取输入和打印输出分开。不需要数组。拟议实施:

#include <iostream>
#include <string>
int main()
{
unsigned tests;
std::cin >> tests;
while (tests--)
{
std::string word;
std::cin >> word;
std::cout << word.substr(0, word.length() / 2) << "n";
}
}

根据Dessus的主张,我想将此代码作为int main((中调用的函数。但是SPOJ不能接受我这个代码(当我在代码块中编译这个代码时,一切都很好(。

#include <iostream>
#include <string>
std::string nowe_slowo(int t)
{
while (t--)
{
std::string word;
std::cin >> word;
std::cout<<word.substr(0, word.length() / 2)<<"n";
}
}
int main()
{
unsigned tests;
std::cin >> tests;
nowe_slowo(tests);
}

最新更新