只要使用 'fstream的'。它忽略了新行,并且像'iostream'一样工作。你只需要跟踪你的矩阵行和列。
//open "myFileName.txt" with an input file stream
std::ifstream inputFile("myFileName.txt");
while(!inputFile.eof()) //Check for end-of-file character
{
//do this while keeping track of your matrix position
inputFile >> M [curRow] [curColumn]
}
inputFile.close();
而且不要忘了,包括图书馆:
#include <fstream>
编辑:>>
运营商也将尝试自动施放的输入为任何类型的您正在使用:
double dTemp;
int iTemp;
std::string sTemp;
std::ifstream in("myFile.txt");
in >> dTemp; //input cast as double
in >> iTemp; //input cast as integer
in >> sTemp; //input cast as string
in.close();
编辑:获取文件的元素数
int temp, numberOfInputs;
while(!inputFile.eof())
{
inputFile >> temp;
++numberOfInputs;
}
inputFile.seekg(0, std::ios::beg); //Go to beginning of file
一旦你有了输入的数量,你可以用它来计算出行数和列数。
是否阵已是N×N的?否则,对于某些输入有多个有效的数组维度......哪一个可以选择? – delnan 2010-11-02 16:52:51
也许我只是误解了你的意图,但我在你的矩阵显示中看到M [2] [0],M [2] [1]和M [2] [2]两次,而不是-2,3和 - 1个文件示例中的值。如果你想帮助人们理解你的问题,你应该清除它。 – haylem 2010-11-02 17:08:20
你也应该知道,用0表示文件的结尾意味着你必须有扩展的逻辑来确定矩阵体内的0是否是一个真正的零或被排除的“结束”零。 – SubSevn 2010-11-02 17:13:52