Code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void printVector (const vector<string>& theVect, vector<bool>& bArray, int nItems){
for (int i = 0; i < nItems; ++i)
if (bArray[i] == true)
cout << theVect[i] << " ";
outFile << theVect[i];
cout << "\n";
outFile << "\n";
}
void nCombination(const vector<string> &Vect,int n, int r){
vector<bool> myBits(n, false); // everything is false now
int count = 1;
for (size_t i = n-1; i >= 0 && count <= r; --i, ++count){
myBits[i] = true;
}
do // start combination generator
{
printVector(Vect, myBits, n );
} while (next_permutation(myBits.begin(), myBits.end()));; // change the bit pattern
}
void nPermutation(vector<string> o, int r){
do {
for(int count = 0; count < r; count++){
cout << o[count] << " " ;
outFile << o[count] << " ";
}
cout<< endl;
outFile << endl;
}
while (next_permutation(o.begin(), o.end()));
}
int main(int argc, char** argv) {
int numofOps;
char Op;
int n;
int r;
string line;
ifstream myFile("infile.dat");
myFile >> numofOps;
myFile.ignore(1,'\n');
ofstream outFile;
outFile.open ("example.txt");
for(int q = 0; q < numofOps; ++q){
myFile.get(Op);
myFile >> n;
myFile>> r;
vector<string> original(n);
for(int i = 0;i <= n - 1; i++){
myFile.ignore(1,'\n');
myFile >> original[i];}
myFile.ignore(1,'\n');
sort(original.begin(), original.end());
cout<< '\n'<< endl;
if(Op == 'P'){
nPermutation(original, r);
}
else{
if(Op == 'C')
nCombination(original,n,r);
else
cout << "Incorrect Input" << endl;
}
original.clear();
}
outFile.close();
return 0;
}
我的代码有效,但当我添加outFile将所有内容写入名为example的文件时,它无法正常工作。如何打印出函数的结果?
例子真是太棒了!!
答案 0 :(得分:1)
一个迫在眉睫的问题:
if (bArray[i] == true)
cout << theVect[i] << " ";
outFile << theVect[i];
Python是我所知道的唯一使用缩进来控制语句阻塞的语言。在基于C语言中,您应该使用大括号:
if (bArray[i] == true) {
cout << theVect[i] << " ";
outFile << theVect[i];
}
最重要的是,您提供的代码甚至不应该编译。您在outFile
中创建main()
作为本地参数,然后尝试在其他无法访问的函数中使用它。
你应该通过将它移出main()
使其成为“全局”,这样每个函数都可以看到它(不明智,但可能是这里最快的解决方案),或者将它作为参数传递给每个需要的函数用它。
对于前者,您可以使用:
using namespace std;
ofstream outFile; // taken from main().
对于后者,需要为每次调用printVector()
,nCombination()
和nPermutation()
添加它,并修改这些函数以便他们接受它,例如:
void nPermutation (
vector<string> o,
int r,
ofstream os
) {
os << "blah blah blah\n";
}
:
nPermutation (original, r, outFile);