The problem is the structure of your for
loop. I'm not sure what you think your condition means, but here's how it should look:
for (std::size_t i = 0; i < 10; ++i) {
This increments the index value i
from 0
to 9
(inclusive). You can then check the value of fooDevice[i]
.
At the moment, it seems you are trying to overwrite every element of the array with the new string. I'm not sure how you know how full the array is at any given time. Let's suppose you stop when you get to the first empty string:
for (std::size_t i = 0; i < 10; ++i) {
if (myString == fooDevice.id[i]) {
// already there, stop looping
break;
}
else if (fooDevice.id[i].empty()) {
// none of the currently set elements matches
fooDevice.id[i] = myString;
temp << myString << '\n';
break;
}
}
You could also replace this with a range-based-for
:
for (auto& deviceId: fooDevice.id) {
if (myString == deviceId) {
// already there, stop looping
break;
}
else if (deviceId.empty()) {
// none of the currently set elements matches
deviceId = myString;
temp << myString << '\n';
break;
}
}
Better yet, use a std::vector
with std::find
from the <algorithm>
header. (Warning: untested code):
struct Device {
// ...
std::vector<std::string> id;
// ...
};
// ...
auto foundId = std::find(fooDevice.id.begin(), fooDevice.id.end(), myString);
if (fooDevice.id.end() == foundId) {
// not already there
fooDevice.id.push_back(myString);
temp << myString << '\n';
}
It seems you are a bit confused about the difference between C and C++ as well:
- The C++ version of
<stdio.h>
is <cstdio>
, but you don't need it here at all (and you usually don't in a C++ program).
- You don't need to
typedef
the name of a struct
in C++, just do struct Device { ... };
And regarding C++ style, please reconsider your use of what are often considered bad practices: using namespace std;
and endl
.