In the following small c++ program I'm trying to add '0' (zero characters) until the number of characters in the users input can be evenly divided by 3. I'v got it working except that it doesn't work when only on character is feed to the program.

input -> 123 -> nothing to change, good
input -> 1234 -> becomes "001234", good
input -> 12345 -> becomes "012345", good
input -> 12 -> becomes "012", good
input -> 1 -> get continues prompt, bad
input -> 5 -> get continues prompt, bad

Any idea on why this is happening?

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>

int main(int argc, char *argv[])
{
    char string[13] = "";
    strcpy(string, argv[1]);

    while(strlen(string) % 3 != 0 || strlen(string) < 3)
    {
        int position = strlen(string);
        for(int i = 0; i < strlen(string); i++)
        {
            string[position + 1] = string[position];
            position--;
        }

        string[0] = '0';
    }

    int groups = strlen(string) / 3;

    std::cout << string << std::endl;
    std::cout << groups << std::endl;

    return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>

int main(int argc, char *argv[])
{
    char string[13] = "";
    strcpy(string, argv[1]);

    while(strlen(string) % 3 != 0 || strlen(string) < 3)
    {
        int position = strlen(string);

        if(strlen(string) == 1)
        {
            for(int i = 0; i <= strlen(string); i++)
                    {
                            string[position + 1] = string[position];
                            position--;
                    }
        }

        for(int i = 0; i < strlen(string); i++)
        {
            string[position + 1] = string[position];
            position--;
        }

        string[0] = '0';
    }

    int groups = strlen(string) / 3;

    std::cout << string << std::endl;
    std::cout << groups << std::endl;

    return 0;
}

In the following small c++ program ...

Use std::string instead?

#include <iostream>
#include <string>

int main( int argc, char* argv[] )
{
    for( int i = 1 ; i <argc ; ++i )
    {
        const std::string arg = argv[i] ;

        const auto rem = arg.size() % 3 ;
        const auto nzeroes = rem ? 3-rem : 0 ;

        const std::string sanitized_arg = std::string( nzeroes, '0' ) + arg ;

        std::cout << arg << " => " << sanitized_arg << '\n' ;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.