我有以下代码尝试枚举 字符串。
#include <string>
#include <iostream>
using namespace std;
string base = "000";
char values[] = {'0', '1', '2', '3' }; // Error Here
for (int i = 0; i < base.length(); ++i)
{
for (int j = 0; j < countof(values); ++j)
{
if (base[i] != values[j])
{
string copy = base;
copy[i] = values[j];
cout << copy << endl;
for (int k = i+1; k < base.length(); ++k)
{
for (int l = 0; l < countof(values); ++l)
{
if (copy[k] != values[l])
{
string copy2 = copy;
copy[k] = values[l];
cout << copy2 << endl;
}
}
}
}
}
}
但是如何编译却给出了错误:
test.cc:9: error: expected unqualified-id before 'for'
test.cc:9: error: expected constructor, destructor, or type conversion before '<' token
test.cc:9: error: expected unqualified-id before '++' token
答案 0 :(得分:5)
错误实际上位于for
循环的以下行中:您的代码需要包含在某种函数中,很可能是int main(void)
答案 1 :(得分:3)
你错过了一个主要的。
尝试:
#include <string>
#include <iostream>
using namespace std;
string base = "000";
char values[] = {'0', '1', '2', '3' }; // Error Here
int main() // Added
{ // Added
for (int i = 0; i < base.length(); ++i)
{
for (int j = 0; j < countof(values); ++j)
{
if (base[i] != values[j])
{
string copy = base;
copy[i] = values[j];
cout << copy << endl;
for (int k = i+1; k < base.length(); ++k)
{
for (int l = 0; l < countof(values); ++l)
{
if (copy[k] != values[l])
{
string copy2 = copy;
copy[k] = values[l];
cout << copy2 << endl;
}
}
}
}
}
}
return 0; // Added
} // Added
答案 2 :(得分:2)
我发现了2个主要问题。
1)你没有main()且没有返回代码,理所当然。
2)countof()不存在,你可能正在寻找sizeof()。
#include <string>
#include <iostream>
#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )
using namespace std;
int main(int argc, char *argv[]) {
string base = "000";
char values[] = {'0', '1', '2', '3' }; // Error Here
for (int i = 0; i < base.length(); ++i)
{
for (int j = 0; j < countof(values); ++j)
{
if (base[i] != values[j])
{
string copy = base;
copy[i] = values[j];
cout << copy << endl;
for (int k = i+1; k < base.length(); ++k)
{
for (int l = 0; l < countof(values); ++l)
{
if (copy[k] != values[l])
{
string copy2 = copy;
copy[k] = values[l];
cout << copy2 << endl;
}
}
}
}
}
}
return 0;
}