我想从二维数组C ++中打印出一些值

时间:2011-03-02 13:08:12

标签: c++

我想从txt文件输入数据。 该文件包含二维数组[5] [5] 我怎么能打印出我想要的任何价值? 我不想打印出整个5 * 5数据

#include <iostream>

#include <fstream>
#include <string>


using namespace std;



int main()
{

    double distance[5][5] ;
    string line;

     ifstream ratefile;
                   ratefile.open("a.txt");
     ofstream file;
     if (ratefile.is_open())
      {
    while (! ratefile.eof() )
    {
      getline (ratefile,line);
   ratefile.getline(distance, 25, '*');

    cout << "\nDistance [0][0]" << ": " << distance[0][0];
    cout << "\nDistance [0][1]" << ": " << distance[0][1];
    cout << "\nDistance [0][2]" << ": " << distance[0][2];
    cout << "\nDistance [0][3]" << ": " << distance[0][3];
    cout << "\nDistance [1][0]" << ": " << distance[1][0];
    cout << "\nDistance [1][1]" << ": " << distance[1][1];
    cout << "\nDistance [1][2]" << ": " << distance[1][2];
    cout << "\nDistance [1][3]" << ": " << distance[1][3];

    cout << endl;


    cin.get();



    return 0;
}

2 个答案:

答案 0 :(得分:1)

如果您只想输出一个值而用户应该能够选择一个值,您可以这样做:

int x, y;

cin >> x;
cin >> y;

cout << "\nDistance [" << x << "][" << y << "]" << ": " << distance[x][y];

但你应检查用户是否输入有效数字(0 <= x <4且0 <= y <4)

答案 1 :(得分:0)

缺少部分代码,但您正在打印所需的值。只需删除您不想打印的行。

当然你也可以使用变量:

int x = 2,y = 2;
cout << endl << "Distance [" << x << "][" << y << "] : " << distance[x][y];