Hello. So this program should read N and then N numbers greater than 9 from a file, then if the first two digits of a number are not a perfect square it should delete that number. It kinda does that but it has an error. For example if in the "elempp.in" file I have these numbers:(n = 5) 253 16 225 100 3678, then in the "elempp.out" file, there should be these numbers: 253 16 3678, but in my case, there is an extra 100, so the numbers are: 253 16 100 3678.
#include <sstream>
#include <iostream>
#include <cmath>
bool pp(int x)
{
return sqrt(x) == static_cast<int>( sqrt(x) );
}
int main()
{
// test
for ( int i = 1; i < 100; ++i )
{
if ( pp(i) ) std::cout << i << " ";
}
std::cout << '\n';
std::string data {"5 253 16 225 100 3678"};
std::istringstream f {data};
int n {0};
f >> n;
for ( int i = 0; i < n; ++i )
{
int v {0};
if ( f >> v )
{
while ( 100 <= v ) v /= 10;
if ( pp(v) ) std::cout << v << " ";
}
}
return 0;
}
Perhaps floating point math on your platform is more delicate (or I did too many changes)?
@FraNNkie,
You delete the value in the ith position (lines 28-30). What was in the (i+1)th position gets moved to the ith position ... and hence is never checked because i is then incremented.
It would be safer either to write a sentinel into v[i] (e.g. -1) or have a separate array for your legitimate outputs.
Thanks to both of you I got it to work (@lastchance and @keskiverto). The error in my code was caused by me forgetting to add an instruction after line 30 (i--;)
Code: