Переделать программу под считывание данных из текстового файла. С++
Есть программа, считающая и выводящая перестановки символов строки. Надо переделать ввод и вывод на текстовые файлы.
Например, в текстовом файле input.txt содержится строка "АB", тогда при выполнении программы, в текстовом файле output.txt записывается
2
AB
BA
#include <iostream>
#include <string>
using namespace std;
//Function to print line breaks
// This function takes three parameters:
// 1. string
// 2. initial line index
// 3. the final string index.
int permute(string a, int l, int r)
{
// basic case
if (l == r) {
cout<<a<<endl;
return 1;
} else {
int count = 0;
// permutations
for (int i = l; i <= r; i++)
{
// swap
swap(a[l], a[i]);
// recursion is called
count += permute(a, l+1, r);
// reverse track
swap(a[l], a[i]);
}
return count;
}
}
long long factorial(unsigned n)
{
long f = 1;
while (n) f *= n--;
return f;
}
// driver code
int main()
{
string str;
cout << "Input string from the user: ";
cin >> str;
int n = str.size();
cout << "Number of permutations: " << factorial(n) << endl;
int count = permute(str, 0, n - 1);
return 0;
}
Вы можете использовать классы ifstream и ofstream для чтения и записи файлов соответственно.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//Function to print permutations
int permute(string a, int l, int r, ofstream &output)
{
int count = 0;
if (l == r) {
output << a << endl;
count++;
} else {
for (int i = l; i <= r; i++)
{
swap(a[l], a[i]);
count += permute(a, l+1, r, output);
swap(a[l], a[i]);
}
}
return count;
}
long long factorial(unsigned n)
{
long f = 1;
while (n) f *= n--;
return f;
}
int main()
{
string str;
ifstream input("input.txt");
input >> str;
input.close();
int n = str.size();
ofstream output("output.txt");
output << factorial(n) << endl;
int count = permute(str, 0, n - 1, output);
output.close();
return 0;
}
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
int main(){
ifstream fi("input.txt"); ofstream fo("output.txt");
string s; int n=0; fi>>s; sort(s.begin(),s.end());
do fo<<s<<endl; while(n++,next_permutation(s.begin(),s.end()));
fo<<"n="<<n<<endl; fi.close(); fo.close();}