您在C++所以不要用scanf
,喜欢std::ifstream
代替。
#include <fstream>
using namespace std;
ifstream file("input.txt");
int x, y, z;
float eta, phi;
// Read you file until the end
while(file >> x >> y >> z >> eta >> phi)
{
// Print the values
cout << "x : " << x << " y :" << y << " z : " << z << " eta : " << eta << " phi : " << phi << endl;
}
如图所示阿尔钦Tsirunyan,你也可以使用一个struct
的数据存储与vector
。这取决于你想要对你的数据做什么。
一个结构的优点是你有一个实体代表与所有数据的统一。你可以重载一个operator>>
来阅读更清晰的代码文件。
的代码看起来就像这样:
#include <fstream>
#include <vector>
using namespace std;
struct s_Data
{
int x, y, z;
float eta, phi;
};
istream& operator >> (istream& iIn, s_Data& iData)
{
return iIn >> iData.x >> iData.y >> iData.z >> iData.eta >> iData.phi;
}
ifstream file("input.txt");
// Read you file until the end
s_Data data;
vector<s_Data> datas;
while(file >> data)
{
// Print the values
cout << "x : " << data.x << " y :" << data.y << " z : " << data.z << " eta : " << data.eta << " phi : " << data.phi << endl;
// Store the values
datas.push_back(data);
}
这里s_Data
代表你河旁你想要的5个值。 vector<s_Data>
代表文件中读取的所有值。你可以通过下面的方式阅读它:
unsigned int size = datas.size();
for (unsigned int i = 0; i < size; i++)
cout << datas[i].x; // read all the x values for example
avector中的每一行或向量中的每个数字? – Vijay
不要在C++中使用'scanf',你有'std :: cin'。 – nouney
你说你的尝试不行,但是出了什么问题?匆匆一瞥表明它应该正确读取值,那么它将它们存储在你失败的向量中? – Jules