主题:[讨论]一个错误的程序——文件的读取
在源文件所在的文件夹里,有f1.txt ......f5.txt等文件
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a,i;
for(i=0;i<6;i++){
switch(i)
{
case 1: ifstream infile("f1.txt");break;
case 2: ifstream infile("f2.txt");break;
case 3: ifstream infile("f3.txt");break;
case 4: ifstream infile("f4.txt");break;
case 5: ifstream infile("f5.txt");break;
}
infile>>a;
cout<<a;
}
system("pause");
return 0;
}
上面的是错的,但下面的就对了。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a,i;
for(i=0;i<6;i++){
switch(i)
{
case 1: ifstream infile("f1.txt");infile>>a;break;
case 2: ifstream infile("f2.txt");infile>>a;break;
case 3: ifstream infile("f3.txt");infile>>a;break;
case 4: ifstream infile("f4.txt");infile>>a;break;
case 5: ifstream infile("f5.txt");infile>>a;break;
}
cout<<a;
}
system("pause");
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a,i;
for(i=0;i<6;i++){
switch(i)
{
case 1: ifstream infile("f1.txt");break;
case 2: ifstream infile("f2.txt");break;
case 3: ifstream infile("f3.txt");break;
case 4: ifstream infile("f4.txt");break;
case 5: ifstream infile("f5.txt");break;
}
infile>>a;
cout<<a;
}
system("pause");
return 0;
}
上面的是错的,但下面的就对了。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a,i;
for(i=0;i<6;i++){
switch(i)
{
case 1: ifstream infile("f1.txt");infile>>a;break;
case 2: ifstream infile("f2.txt");infile>>a;break;
case 3: ifstream infile("f3.txt");infile>>a;break;
case 4: ifstream infile("f4.txt");infile>>a;break;
case 5: ifstream infile("f5.txt");infile>>a;break;
}
cout<<a;
}
system("pause");
return 0;
}