每当我将 astring
和 avector
放在同一行时,字符串就会变为空。在我的代码中,
string line, s1, s2;
vector<pair<string,int> > binaryvector;
ifstream filename(uncompr_filename.c_str());
如果我做
while(getline(filename, line))
{
s1 = line.c_str();
s2 = binaryvector[0].first.c_str();
cout << s1 << endl;
cout << s2 << endl;
}
它打印 s1 和 s2 的值。但如果我这样做,
while(getline(filename, line))
{
s1 = line.c_str();
s2 = binaryvector[0].first.c_str();
cout << s1 << s2 << endl;
}
它只打印 s2 字符串。我哪里错了?这只是为了说明问题。我实际上想要做的是使用 if(s1 == s2) 比较 s1 和 s2。但是如果我这样做,它会返回 false,因为 s1 似乎没有任何内容并且不等于 s2 字符串。
完整的代码。
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
#define DICTIONARYSIZE 4
using namespace std;
typedef map<string,int> Instruction_Binaries;
struct val_greaterthan : binary_function < pair<string,int>, pair<string,int>, bool >
{
bool operator() (const pair<string,int>& x, const pair<string,int>& y) const
{return x.second > y.second;}
}val_gt;
int main(int argc, char *argv[])
{
int c, i;
Instruction_Binaries binary_count;
string uncompr_filename, compr_filename, outfilename;
if(argc <= 3)
{
cout << "Format is \"./SIM -c original.txt cout.txt\" or \"./SIM -d compressed.txt dout.txt\"" << endl;
return 1;
}
while ((c = getopt (argc, argv, "c:d:")) != -1)
switch (c)
{
case 'c':
(uncompr_filename=optarg);
break;
case 'd':
(compr_filename=optarg);
break;
default:
cout << "Format is \"./SIM -c original.txt cout.txt\" or \"./SIM -d compressed.txt dout.txt\"" << endl;
abort ();
break;
}
ifstream ifile(uncompr_filename.c_str());
string binary, Directory_Index;
while (ifile >> binary){
int index;
++binary_count[binary];
}
vector<pair<string,int> > binaryvector;
copy(binary_count.begin(), binary_count.end(), back_inserter(binaryvector));
sort(binaryvector.begin(), binaryvector.end(), val_gt);
while(ifile >> binary){
int flag = 0;
for(i=0; i<4; ++i){
if(i==0) Directory_Index = "00";
else if(i==1) Directory_Index = "01";
else if(i==2) Directory_Index = "10";
else if(i==3) Directory_Index = "11";
if(binary == binaryvector[i].first){
cout << "001" << Directory_Index << endl;
flag=1;
break;
}
}
if(flag == 0)
cout << binary << endl;
}
return 0;
}