我想从二维数组打印出一些值C++
问题描述:
我想从txt文件输入数据。 该文件包含二维数组[5] [5] 如何打印出我想要的任何值? 我不希望打印出整个5点* 5的数据我想从二维数组打印出一些值C++
#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;
}
答
还有就是代码所缺少的一部分,但你要打印你想要的值。只需删除不想打印的行。
当然,你也可以使用变量:
int x = 2,y = 2;
cout << endl << "Distance [" << x << "][" << y << "] : " << distance[x][y];
答
如果您只想输出一个值和用户应该能够选择一个值,你可以做这样的事情:
int x, y;
cin >> x;
cin >> y;
cout << "\nDistance [" << x << "][" << y << "]" << ": " << distance[x][y];
但是,你应该检查,如果用户输入有效的数字(0 < = X < 4和0 < = Y < 4)
你错过一些线路中的码? – Fox32 2011-03-02 13:11:30
作为一名程序员,如果我想打印出我想要的值,我会打印出我想要的值。如果你想有人回答这个问题,你需要指定问题是什么...... – Lindydancer 2011-03-02 13:12:40
这是家庭作业吗? – Nav 2011-03-02 13:25:57