nested for loops to find number of digits

i am trying to make a program that tells the number of digit/letters in each command line argument eg. if 'hello bruh 4444444' is entered the program will put out '5 4 7'.
currently i don't know how to do this using a nested for loop please help tyty

#include "stdafx.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
int i;

for (i = 0; argv[i][0] != '\0'; i++);
{
int j;
for (j = 0; argv[i][j] != '\0'; j++);
cout << j << endl;
}
}
Last edited on
Your outer loop is wrong. If there are three arrays you should be looking at, do not decide it's time to stop by checking the first char of the 4th array. The 4th array does not exist, so checking the first char of a non-existent array is a bad idea.

argc tells you how many char arrays you need to look at.


Your for loops have nothing in them. Do not put a semi-colon on them.

Bad:
for (i = 0; argv[i][0] != '\0'; i++);

Good:
for (i = 0; argv[i][0] != '\0'; i++)
Last edited on
The last member of the argv array is guaranteed to be NULL.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main(int argc, char **argv) {
    for (int i = 0; argv[i] != NULL; i++) {
        int j = 0;
        for ( ; argv[i][j] != '\0'; j++)
            ;
        std::cout << j << '\n';
    }
    return 0;
}

For the outer loop, start the counter from one (not zero).
argv[0] typically represents the name of the program (though the standard allows this to be an empty string).
argv[1] onwards upto argv[argc-1] are the command line arguments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main( int argc, char* argv[] )
{
    // outer loop: for each command line argument starting with argument one
    for( int i = 1 ; i < argc ; ++i ) // note that there is no semicolon here
    {
        int j ; // character count

        // inner loop: for each character in this argument up to the null character
        // each time through the loop increment j
        for( j = 0; argv[i][j] != '\0'; ++j ) ; // there is a semicolon here
        // at the end of the loop, j has been incremented once for each non-null character

        std::cout << j << ' ' ; // print the number of characters followed by a space
    }

    std::cout << '\n' ; // finally, print a new line
}

http://coliru.stacked-crooked.com/a/8cc50c9f62f6b06c
why not

for( int i = 1 ; i < argc ; ++i )
cout << strlen(argv[i]) << " "; //C string length function replaces inner loop
cout << endl;


Thanks guys i done a bit of editing to polish but thanks for pointing me in the right direction
> /C string length function replaces inner loop

and std::transform replaces the outer loop.
1
2
3
4
5
int main( int argc, char* argv[] )
{
    std::transform( argv+1, argv+argc, std::ostream_iterator<int>( std::cout, " " ), std::strlen ) ;
    std::cout << '\n' ; // finally, print a new line
}

http://coliru.stacked-crooked.com/a/c62712297f257f39
Topic archived. No new replies allowed.