Help with the program
Feb 24, 2018 at 11:19am UTC
Hello everyone. I trying to write a program where the user enters number and counter is moving by that. My problem is how to make a program not start from the very beginning but from next available position. For example, when the user enters 2 , program should go to position 2 and when the user is asked again it should start from position 3. Can someone give me hint how could I get this done? Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <iostream>
using namespace std;
unsigned short availablePosition = 0;
class Counter{
public :
unsigned short position;
char row;
public :
Counter () { row = 'F' ; position = 1;};
void printPosition () {cout << row << position ;};
void moveCounter ();
};
int main (){
Counter c;
c.moveCounter ();
return 0;
}
void Counter::moveCounter(){
int jumps = 0;
Counter startPosition, endPosition;
endPosition.row = startPosition.row;
endPosition.position = startPosition.position;
do {
cout << "Enter number of jumps:\t" ;
cin >> jumps;
endPosition.position = startPosition.position + jumps-1;
while (endPosition.position > 12)
{
endPosition.position -= 12;
startPosition.position = endPosition.position;
startPosition.row++;
}
cout << startPosition.row << endPosition.position << "\n" ;
}while (!(startPosition.row =='K' ) && (endPosition.position = 12));
}
Feb 24, 2018 at 2:14pm UTC
Something along these lines, perhaps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
struct counter {
private :
static constexpr std::size_t NROWS = 10 ; // "ABCDEFGHIJ"
static constexpr std::size_t NCOLS = 12 ; // 1 to 12
// total number of positions
static constexpr std::size_t NUM_POSITIONS = NROWS * NCOLS ;
std::size_t curr_pos = 0 ; // note: zero-based
public :
// return the current col (1 to 12)
std::size_t curr_col() const { return curr_pos%NCOLS + 1 ; } // make it one based
// return the current aow (A to J)
char curr_row() const {
static const char rows[] = "ABCDEFGHIJ" ;
return rows[ curr_pos/NCOLS ] ;
}
// jump by n positions
counter& jump( std::size_t n ) {
// jump back to beginning if NUM_POSITIONS is exceeded
curr_pos = ( curr_pos + n ) % NUM_POSITIONS ;
return *this ;
}
friend std::ostream& operator << ( std::ostream& stm, counter cntr ) {
return stm << cntr.curr_row() << cntr.curr_col() ;
}
};
int main() {
counter cntr ;
std::cout << "initially at " << cntr << "\n\n" ;
std::size_t n ;
while ( std::cout << "#jumps (enter q to quit)? " && std::cin >> n ) {
// C++17: can combine these two into one statement
std::cout << '\n' << cntr << " ==> " ;
std::cout << cntr.jump(n) << "\n\n" ;
}
}
Topic archived. No new replies allowed.