一个C++的文件写问题
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int StrCmp(string a,string b);
int main(int argc, char *argv[])
{
string ches,line,chesa,chesb;
ofstream out("FILEwrite.cpp");
char ch;
for(int i=0;ch!='$';i++)
{
printf("input the strings %d \n",i+1);
cin >> ches;
out << ches;
printf("if you want to go on ,press any key but '$' \n");
cin >> ch ;
}
vector<string> v;
int i,j;
ifstream in("FILEwrite.cpp");
while(getline(in,line))
{
v.push_back(line);
i++;
}
for(i=0;i<v.size();i++)
for(j=i+1;j<v.size();j++)
{
chesa=v[i];
chesb=v[j];
if(StrCmp(chesa,chesb)>0)
{
ches=v[i];
v[i]=v[j];
v[j]=ches;
}
}
ofstream out ("FLLEwrint.cpp"); //A
for(i=0;i<v.size();i++)
out << v[i]<< "\n";
system("PAUSE");
return EXIT_SUCCESS;
}
int StrCmp(string a,string b)
{
int i;
for(i=0;i<a.size()&&i<b.size();i++)
if(a[i]>b[i])
return 1;
else
if(a[i]<b[i])
return -1;
}
有个编译错误是这样的: redeclaration of `std::ofstream out'
但若把A句去掉,编译就成功了,怎么回事,觉得很奇怪
[解决办法]
out变量重复定义了
[解决办法]
这不很明显么?你函数开头不是定义了ofstream out("FILEwrite.cpp"); 么?同一个作用域里你不能定义同名变量
ofstream out ("FLLEwrint.cpp");
这里你又定义一个out,和前面冲突,自然会报错