Why is my string undefined?

1.2k Views Asked by At

The error says s is undefined at this point in my code:

cout << "Enter the string : ";

cin >> s;

How can I fix that?

Also, another error at my second bracket says "expecting a ;". What can I do to fix that?

Here's my full code:

#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;
            }
4

There are 4 best solutions below

0
On BEST ANSWER

You have declared your function inside the main block, which is causing the compilation error. Declare it outside as-

#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;
 }
0
On

I don't see the place where you define the string s. C++ is declarative. You MUST declare all variables before using them. It's different from PHP, for instance, where initializing a variable is equivalent to declaring it.

0
On

Take a look at the nesting of your parenthesis as well. Looks like you have your permutation function declared inside of main(). That might confuse the compiler.

0
On

void permutation(string s, int i, int n) is defined inside main . Place it outside and check . The following is wrong

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