注册 登录
编程论坛 C++教室

.txt文件的读取

y605302737 发布于 2013-02-02 22:06, 401 次点击
大家好:我写了个读取.txt的程序,不知道错在哪,大家帮忙看下
文件是yyy.txt,内容
0 0 1 2 3 1 2 3
2 1 2 2 3 2 1 3
我想读到一个二维数组,再在终端显示,但运行完下面的程序提示:yyy.exe停止工作    出现了一个问题,导致程序停止正常工作。


#include <iostream>
#include <string >
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
   
    ifstream infile;
    infile.open("yyy.txt");
    if(!(infile.is_open()))
        cout<<"cannot open"<<endl;
    int suzu[1][7];
    int value;
    infile>>value;
    while(infile.good())
    {
        for(int i=0;i!=2;i++)
        {
            for(int m=0;m!=8;m++)
                suzu[i][m]=value;
        }
            infile>>value;
    }
    if(infile.eof())
        cout<<"end of file reach"<<endl;
    for(int i=0;i!=2;i++)
    {
        for(int m=0;m!=8;m++)
            cout<<"suzu[i][m] = "<<suzu[i][m]<<endl;
    }
    infile.close();
    return 0;
}
6 回复
#2
zhuanjia02013-02-03 00:01
程序代码:
#include <iostream>
#include <string >
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
   
    ifstream infile;
    infile.open("yyy.txt");
    if(!(infile.is_open()))
        cout<<"cannot open"<<endl;
    int suzu[1][7];    //你的二维数组应该是2*7 所以应该改成 int suzu[2][7];
    int value;
    infile>>value;
    while(infile.good())
    {
        for(int i=0;i!=2;i++)
        {
            for(int m=0;m!=8;m++)
                suzu[i][m]=value;
        }
            infile>>value;
    }
    if(infile.eof())
        cout<<"end of file reach"<<endl;
    for(int i=0;i!=2;i++)
    {
        for(int m=0;m!=8;m++)
            cout<<"suzu[i][m] = "<<suzu[i][m]<<endl;
    }
    infile.close();
    return 0;
}


另外,纠正你的一个小错误,数组是shuzu不是suzu……
#3
y6053027372013-02-03 16:26
我将程序改了下,可以运行,程序如下,但输出不正确了
程序代码:
#include <iostream>
#include <string >
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
   
    ifstream infile;
    infile.open("yyy.txt");
    if(!(infile.is_open()))
        cout<<"cannot open"<<endl;
    int shuzu[2][8];
    int value;
   
    for (int i=0;i!=2;i++)
    {
        for(int m=0;m!=8;m++)
        {
            infile>>value;
            while(infile.good())
            {
                shuzu[i][m]=value;

                infile>>value;

            }
        }
      
    }
    if(infile.eof())
        cout<<"end of file reach"<<endl;
    for(int i=0;i!=2;i++)
    {
        for(int m=0;m!=8;m++)
            cout<<"shuzu["<<i<<"]"<<"["<<m<<"]"<<" = "<<shuzu[i][m]<<endl;
    }
    infile.close();
    return 0;
}

终端输出:
只有本站会员才能查看附件,请 登录


[ 本帖最后由 y605302737 于 2013-2-3 16:27 编辑 ]
#4
lintaoyn2013-02-03 20:44
程序代码:
for (int i=0;i!=2;i++)
    {
        for(int m=0;m!=8 && infile.good();m++)
        {
            infile>>value;
            shuzu[i][m]=value;   
        }
        
    }
#5
y6053027372013-02-03 22:26
回复 4楼 lintaoyn
谢谢,结果终于对了。
#6
SwanK2013-02-14 15:01
回答的好!!
#7
SwanK2013-02-14 15:01
系统时间不对,怎么才2月3
1