首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

简单的读文件有关问题:帮小弟我看看按行读文件如何错了

2012-03-18 
简单的读文件问题:帮我看看按行读文件怎么错了文件内容location81barrier847464程序ifstreaminfile( 1.tx

简单的读文件问题:帮我看看按行读文件怎么错了
文件内容
location   8   1
barrier     8   4   7   4   6   4
程序
ifstream   infile( "1.txt ");
sting   environment;
while   (infile> > environment)   {


  if   (environment== "barrier ")  
{

  while   (!infile.eof())
  {
  int   temp3,temp4;
  infile> > temp3> > temp4;
  a[temp3][temp4]= '1 ';
 

  }


}
读不出来,为什么

[解决办法]
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
char a[10][10];
ifstream infile( "1.txt ");
string environment;
while (infile> > environment)
{
if (environment== "barrier ")
{

while (!infile.eof())
{
int temp3,temp4;
infile> > temp3> > temp4;
a[temp3][temp4]= '1 ';
cout < <a[temp3][temp4] < < ' ';
}


}
}
return 0;
}
[解决办法]
用getling写的程序
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
ifstream inifile;
inifile.open( "c://123.txt "); //读入文件路径
if(!inifile)
{
cerr < < "file is not open " < <endl;
}
else
{
string line;
int LineNO(0); //行编号
while(getline(inifile,line)) //从文件读入并判断读入内容
{
istringstream input(line);
string word( " ");

if(input> > word)
{

cout < <++LineNO < < ": ";
if(word== "barrier ")
{
int val1,val2;

while(input> > val1> > val2)
{
cout < < "( "
< <val1 < < " " < <val2
< < ") "
< < " ";
//此处已读出对应的数据
//写入你的处理程序
}
}
else
{
cout < < "This Line is Bad Data! ";
}
cout < <endl;
}
}
}
inifile.close();
inifile.clear();
system( "PAUSE ");
return EXIT_SUCCESS;
}

你的 " "dd 4 " 主要应为循环
while (!infile.eof()) <---此处的判断条件 你的文件结束符
{
int temp3,temp4;
infile> > temp3> > temp4;
a[temp3][temp4]= '1 ';
}
"barrier 8 4 7 4 6 4 "当读入该行输入后,并没有读到结束符号
故程序循环没有结束
infile> > temp3> > temp4;
读入 "dd 4 "则会出现错误,即没有判断 "dd "这个条件

热点排行