string input/output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <string>
#include <iostream>

using namespace std;

void string_permutation(std::string& x, std::string& permute)
{
     if(x.empty())
     {
                  std::printf("%s \n", permute);        <<<< other problem
                  return;
     }
     
     for(int i=0; i<x.size(); ++i)
     {
             std::string y = x;
             y.erase(i,1);
             std::string permute2 = permute;
             permute2 += x.at(i);
             string_permutation(y, permute2);
     }
}

int main()
{
    system ("color 0A");
    
    string input;
    printf("Enter permutation: ");
    scanf("%s", input);                  <<<< here is the problem
    std::string  x = input;
    std:string permute;
    
    string_permutation(x, permute);
    
    system("PAUSE");
    return 0;
}


why won't it let me read the string properly? i don't understand why it just doesn't work.
Please don't tell me to use getline (cin, input); unless there's no other way. I have something against cin and cout.
Also while trying to actually printf my permutation i get the same problem.
Sorry if i seem like a total noob, i'm new to c++ :L
I have something against cin and cout.

However, cin seems so simpler in this case.

And considering that you are using the std namespace, you do not need to have std:: in front of everything.
Last edited on
Line 28 defines a C++ string.
Line 30 requires a C-string.

Line 10 is similar, but can be fixed with the .c_str() function.
Last edited on
I'll cin then, thanks anyway (:
The C io functions (scanf, printf) take char arrays, not string objects. Since string objects do not exist in C.

The C++ versions (cin, cout) take string objects.

So if you want to use strings (which is good, they're useful and less error prone than char arrays), then it's best if you just bite the bullet and use cin/cout. I'm not crazy about iostream myself... it certainly has its share of problems... but don't needlessly shut it down. It's still a good tool.
It's simple enough to put something like

1
2
    char  input[100];
    scanf("%s", input);

or whatever max length you require.

I'm not familar with scanf, I don't know whether you can specify a length to avoid possible overflow.

After that, convert to a C++ string if you so wish.
Yes that is one option.

1
2
3
4
5
6
7
8
// Option A:
string input;
getline( cin, input );

// Option B:
char temp[100];
scanf("%s", temp);
string input = temp;


But again, I really advise you just suck it up and use cin (option A). No risk of buffer overflow, no need for the temporary buffer, easier, etc.
Topic archived. No new replies allowed.