Recently I coded a program to choose k numbers from the string in order from left to right to print out the number that has k characters and the smallest that can be made from the string itself for example : Input : 3 89678982 Output: 672 Then my code didn't print at all!! Code :
#include<bits/stdc .h>
using namespace std;
int k,j=0,i;
string s;
int main() {
cin>>k>>s;
for(int i=0;i<s.size();i ) s[i]-=48;
int the2=0;
int Min=s[0];
while(j<0) {
for(i=the2;i<s.size();i ) {
if(Min>s[i])
{
Min=s[i];
break;
}
}
the2=i;
Min=s[i 1];
cout<<Min;
j ;
}
}
Why did this happen and how do I fix it?
CodePudding user response:
For starters this condition of the while loop
while(j<0) {
evaluates to false at once because the variable j was initialized by 0.
int k,j=0,i;
Also this for loop
for(i=the2;i<s.size();i ) {
if(Min>s[i])
{
Min=s[i];
break;
}
}
finds the first character that is less than Min initially equal to the value s[0]. But you need to find the minimal value of the string in the range [0, s.length() - k 1)
That is the program does do what is described in the assignment.
It seems you mean something like the following.
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string s;
size_t k = 0;
std::cin >> k >> s;
if (not ( s.size() < k ))
{
auto it = std::begin( s );
for (size_t i = 0; i < k; i )
{
it = std::min_element( it,
std::prev( std::end( s ), k - i - 1) );
std::cout << *it ;
}
std::cout << '\n';
}
}
If to enter
3 89678982
then the output will be
672
If to use a for loop instead of calling the standard algorithm std::min_element then program can look the following way
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string s;
size_t k = 0;
std::cin >> k >> s;
if (not ( s.size() < k ))
{
std::string::size_type pos = 0;
for (size_t i = 0; i < k; i )
{
for (auto j = pos; j < s.size() - k i 1; j )
{
if (s[j] < s[pos]) pos = j;
}
std::cout << s[pos ];
}
std::cout << '\n';
}
}
CodePudding user response:
You don't print because j=0 so the while loop's condition (j<0) is false from the beginning. So it's body will not be executed at all. And your cout is inside that loop
