我不确定我会怎么做。我有一个数组,每行有几个值。例如,有一个'name'值,'id'值和一些其他值。我正在读另一个文本文件,它有一个数字,我想要“找到”数组并编辑它。我不确定我是否正确解释它,但比方说,新的文本文件说。
2000 -1.6
我希望找到ID值为“2000'
的'数组'。假设Array[3]
(使用Array作为我的数组的示例名称)的ID值为2000
。如何使程序“知道”Array[3]
具有相同的值?我想让它查找与文本文件中的行具有相同ID的行。
此外,有没有办法将'-1.6'
读作1.6
的整数,但作为负数而不是专门将其单独列出?如果我的解释很奇怪,我很抱歉,但我想不出任何其他说法。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct person
{
string firstname;
int id;
double height;
double weight;
double bmi;
double change;
};
void getdata (person *array, person *ptr);
void printData (person *array, person *ptr);
void calculateBMI (person *array, person*ptr);
void getdata2 (person *array, person *ptr);
int main()
{
person array[13];
person *ptr;
ptr = &array[0];
getdata(array, ptr);
calculateBMI(array, ptr);
printData(array, ptr);
}
void getdata (person *array, person *ptr)
{
ifstream inData;
inData.open("peeps.txt");
while(!inData.eof())
{
for(ptr = &array[0]; ptr < &array[13];ptr++)
{
inData >> ptr->firstname >> ptr->id
>> ptr->height >> ptr->weight;
}
}
}
void printData (person *array, person *ptr)
{
cout << "Name" << " ID" << " Height"
<< " Weight " << "BMI" << endl;
for(ptr = &array[0]; ptr < &array[13];ptr++)
{
cout << ptr->firstname << " "<< ptr->id
<< " "<< ptr->height << " "<< ptr->weight <<
" "<< ptr->bmi << endl;
}
}
void calculateBMI (person *array, person*ptr)
{
for(ptr = &array[0]; ptr < &array[13];ptr++)
{
ptr-> bmi = 703*(ptr->weight/((ptr->height)*(ptr->height)));
}
}
void getdata2 (person *array, person *ptr)
{
ifstream inData;
string filename;
int size;
cout << "Select from file 'A', 'B', or 'C'" << endl;
cin >> filename;
if (filename == "a" || filename == "A")
{
inData.open("A.txt");
cout << "Opening A.txt..." << endl;
size = 17;
}
if (filename == "b" || filename == "B")
{
inData.open("B.txt");
cout << "Opening B.txt..." << endl;
size = 9;
}
if (filename == "c" || filename == "C")
{
inData.open("C.txt");
cout << "Opening C.txt..." << endl;
size = 12;
}
else
{
cout << "You have entered an incorrect filename." << endl;
}
while (size > 0)
{
size--;
}
}
答案 0 :(得分:0)
std :: find_if将执行您想要的操作。
#include <iostream>
#include <algorithm>
struct X { int id; int val; };
class isTarget {
public:
isTarget(int target): target_(target) {}
bool operator() (X &item) { return item.id == target_; }
private:
int target_;
};
int main()
{
X x[] = { {1000, 1}, {2000, 2}, {3000, 3}, {4000, 4} };
X* ele = std::find_if(x, x+4, isTarget(3000)); // this does the work
std::cout << ele->val;
return 0;
}