Alon Shmiel
Alon Shmiel

Reputation: 7121

for loop: a string passes from "0" to "9"

I want to write a for loop that passes the strings for 0 till 9:

for (string j = "0"; j < "10"; j++) {

}

but it doesn't know the operator ++ (it gets an integer (1) and not a string "1").

I think to write: j+="1", but then j will be "01" and then "011"...

p.s. I don't want to use functions of #include <string> or something else. (stoi, etc)

any help appreciated!

Upvotes: 1

Views: 755

Answers (6)

fatihk
fatihk

Reputation: 7929

you can use atoi with:

#include <stdlib.h> // or #include <cstdlib>

for (int j = atd::atoi("0"); j < std::atoi("10"); j++) {

}

Upvotes: 0

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58291

You can do like j[0]++ to increase first char to next ascii value. but this is only for '0'-'9'

edit: Just an idea, not a perfect code: for 0 to 20;

   i = 0;
   (j > "9") && (i==0) ? j[i]++ : (++i, j="10");

Upvotes: 1

kassak
kassak

Reputation: 4194

Not that way, but...

char x[]={'0',0};
for(; x[0] <= '9'; ++x[0])
{
}

Edit: 0..99 version

char x[]={'0','0',0};
int stroffs = 1;
for(; x[0] <= '9'; ++x[0])
{
   for(x[1] = '0'; x[1] <= '9'; ++x[1])
   {
     char * real_str = x + stroffs;
   }
   stroffs = 0;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Do your iterations with integers, and convert them to strings inside the loop, like this:

// Your loop counter is of type int
for (int i = 0 ; i != 10 ; i++) {
    // Use string stream to convert it to string
    ostringstream oss;
    oss << i;
    // si is a string representation of i
    string si = oss.str();
    cout << si << endl;
}

This works for any kind of integers without limitations.

Here is a short demo.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409482

Loop with integers, then manually convert it to a string?

Like

for (int i = 0; i < 10; i++)
{
    string j(1, '0' + i);  // Only works for single digit numbers
}

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258678

With your constraints (although I have no idea how you use string without #include <string>):

const char* x[] = 
{
    "0", "1", .... , "10"
}

for ( int i = 0 ; i <= 10 ; i++ )
{
    x[i]....
}

Upvotes: 0

Related Questions