【问题标题】:Why is my string undefined?为什么我的字符串未定义?
【发布时间】:2015-06-18 03:24:04
【问题描述】:

错误提示 s 在我的代码中此时未定义:

cout << "Enter the string : ";

cin >> s;

我该如何解决这个问题?

另外,我的第二个括号中的另一个错误是“期望一个;”。我能做些什么来解决这个问题?

这是我的完整代码:

#include <stdafx.h>
#include <cctype>    
#include <iostream>
#include <string>
using namespace std;
int main()
{
    void permutation(string s, int i, int n)
    {
        int j;
        if (i == n)
            cout << s << "\t";
        else
        {
            for (j = i; j < s.length(); j++)
            {
                swap(s[i], s[j]);
                permutation(s, i + 1, n);
                swap(s[i], s[j]);

                cout << "Enter the string : ";
                cin >> s;
                cout << endl << "The permutations of the given string : " << endl;
                permutation(s, 0, s.length() - 1);
                cout << endl;
            }

【问题讨论】:

  • 先修复first错误。您似乎正试图在您的 main 函数中声明一个新函数 (permutation)。这是您需要解决的第一件事。否则,编译器在看到第二个{ 时会感到非常困惑,因此您无法相信它在此之后发现的任何错误。
  • 你的代码完全崩溃了,为什么void permutation(string s, int i, int n)main中?
  • 代码甚至无法编译.....
  • main() 不表示模块的主要范围区域。在 C/C++ 中,main() 是一个入口点函数。如果你想定义一个函数,就在外面做。

标签: c++ permutation


【解决方案1】:

您在主块中声明了您的函数,这导致了编译错误。在外面声明它 -

#include <cctype>    
#include <iostream>
#include <string>
using namespace std;
void permutation(string s, int i, int n)

{

int j;

if (i == n)

cout << s << "\t";

else

{

for (j = i; j < s.length(); j++)

{

swap(s[i], s[j]);

permutation(s, i + 1, n);

swap(s[i], s[j]);

}
}
}
int main()
{ 
 string s;
 cout << "Enter the string : ";

 cin >> s;

 cout << endl << "The permutations of the given string : " << endl;

 permutation(s, 0, s.length() - 1);

 cout << endl;
 }

【讨论】:

    【解决方案2】:

    我没有看到你定义字符串 s 的地方。 C++ 是声明性的。您必须在使用它们之前声明所有变量。它与 PHP 不同,例如,初始化变量等同于声明它。

    【讨论】:

      【解决方案3】:

      也看看括号的嵌套。看起来您在 main() 中声明了置换函数。这可能会使编译器感到困惑。

      【讨论】:

        【解决方案4】:

        void permutation(string s, int i, int n) 在 main 中定义。将其放在外面并检查。以下是错误的

        int main()
        {
        void permutation(string s, int i, int n)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-19
          • 1970-01-01
          • 2022-11-12
          • 1970-01-01
          • 1970-01-01
          • 2017-12-03
          • 1970-01-01
          相关资源
          最近更新 更多