How to count input arguments? (Beginners trying to learn C++ here, sorry for the long paragraph)

Hi, I am trying to count the characters from input argument phrase "Hello World 123.54", I have tried the following codes:

int i = 0;
for (i = 0; argv[1][i] != '\0'; i++)
{
cout << argv[1][i] << endl;
}

The results that I got is:
H
e
l
l
o

And now I'm trying to tell the program to count how many words there are, in this case 5, and then display it, I am wondering how should I approach this and how should I do it?

I have attached the original problem below.


Using the input argument phrase ‘Hello World 123.54’, extend on the program you just developed so that it now counts the number of characters entered in the first argument and displays the number to the console. Argument one (‘Hello’) should result in the number 5 being displayed to the console screen. It should be displayed on a separate line with no other characters or text.Hint: Consider writing a ‘for’ loop that searches argv[1] for the null-terminator '\0' characterin the first argument. Depending on how you write the condition for the ‘for’ loop expression, you might need to use Not equal ‘!=’ comparison operator. To access the individual characters in the first argument you might find it easier to use multidimensional array index notation. For example the third character in the first argument can be accessed by: cout << argv[1][2]; Remember that you can use a variable to index the array by replacing the ‘2’ with ‘i’ and using the ++ operator to increase the value of ‘i’ each time the for loop executes. ‘i’ should be defined as an integer.Confirm that when you change the input argument phrase you program counts the correct number of characters in the first argument.
Last edited on
Instead of displaying the character inside the for loop just count it and after the loop print the count.
Hello Anonymous2018,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second lint to be helpful.

The first line of the instructions refers to a program that you have already done. So it would be a good idea to post that code so all can see what you have to start with. It is easier to save that code to a different file or project than to reewrite the whole program.

This way Thomas1965's suggestion can be better directed to your program..

A suggestion: A nested for loop would be helpful where the outer for loop is based on the valuse of "argc" to process all there or more words.

Hope that helps,

Andy
Hello Anonymous2018,

Here is another hint. Breaking up the instructions in to different parts makes it easier to see what the program needs to do. And if you print it to paper you can check off what you have done.


Using the input argument phrase ‘Hello World 123.54’, extend on the program you just developed so that it now
counts the number of characters entered in the first argument and displays the number to the console.

Argument one (‘Hello’) should result in the number 5 being displayed to the console screen. It should be displayed
on a separate line with no other characters or text.

Hint: Consider writing a ‘for’ loop that searches argv[1] for the null-terminator '\0' characterin the first
argument. Depending on how you write the condition for the ‘for’ loop expression, you might need to use
Not equal ‘!=’ comparison operator. To access the individual characters in the first argument you might find it
easier to use multidimensional array index notation. For example the third character in the first argument can
be accessed by: cout << argv[1][2]; Remember that you can use a variable to index the array by replacing the
‘2’ with ‘i’ and using the ++ operator to increase the value of ‘i’ each time the for loop executes.
‘i’ should be defined as an integer.

Confirm that when you change the input argument phrase you program counts the correct number of characters in
the first argument.


Hope that helps,

Andy
Thank you for the hints and suggestions. And here are the codes which are applied prior to the one I posted

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
#include "stdafx.h"
#include<iostream>

using namespace std;

int
main(int argc, char *argv[])
{
	cout
		<< argc << endl;
	//task2 
	if (argc == 1)
	{
		cout
			<< "One argument\n" << endl;
	}
	else if (argc == 2)
	{
		cout
			<< "two arguments\n" << endl;
	}
	else
	{
		cout
			<< "more than two arguments\n" << endl;
	}
	//task3 
	cout
		<< "argument one = " << argv[1] << endl;
	cout
		<< "argument two = " << argv[2] << endl;
	cout
		<< "argument three = " << argv[3] << endl;
	//task4 
	int y = 0;
	for (y = 0; argv[1][y] != '\0'; y++)
	{
		cout << argv[1][y] << endl;
	}


Basically the argv[1], argv[2] and argv[3] are Hello, World, 123.45 respectively. Basically what they required me to do is to display the world first, and then display numbers based on the number of characters so it would look something like
5
5
6
in the cmd.
Hello Anonymous2018,

At line 36 create an outer for loop based on the value of "argc" to process all the words.

The "cout' statements of "task 3" can be eliminated or commented out since this is done in "task 4. As Thomas1965 suggested add a variable inside the inner for loop to keep a count of the letters printed. Then after the inner for loop print the count on a separate line. Also do not forget to zero "count" before the next time through the inner for loop.

Hints:

The compiler does not care about extra white space. but the "cout" statements are better written as one line as an example: cout << argc << endl;. Then some day if you chain enough together in a "cout" statement you can break that up in separate lines as:

1
2
3
4
std::cout << "something to print "
	<< aVariable
	<< "More text"
	<< another Variable << std::endl;
Instead of one long line, that might break up where you do not want it to, you break up the line where you want to an make it easier to read.

To shorten the program the "if/else" statements could be shortened to
1
2
3
4
5
6
if (argc < 2)
{
	std::cout << "\n Command line does not contain enough words to work with." << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(5));  // Requires header files "chrono" and "thread"
	exit(1);
}

The second line puts a pause in the program to allow the user time to read the error message before the program ends, which could close the console window early. The only part you have to worry about is the 5 which is the number of seconds the pause is for. This is a whole number.

The third line could also be "return 1;" either works. Zero means that the program ended normally and any number greater than zero denotes a problem. With multiple "exit" or "return" statements the number can help you find where the problem is.

I use this code just before the "return" in main to keep the console open before the program ends:
1
2
3
4
// The next line may not be needid. If you have to press enter to see the prompt it is not needed.
//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();


Hope that helps,

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

int main( int argc, char* argv[] )
{
    if( argc > 1 ) // if there is a first argument
    {
        int char_cnt = 0 ; // count of characters in the first argument argv[1]

        // for for each character in argv[1], up to, not including the
        // terminating null character, increment char_cnt
        for( int i = 0 ; argv[1][i] != 0 ; ++i ) ++char_cnt ;

        // displayed on a separate line with no other characters or text
        std::cout << char_cnt << '\n' ;
    }
}
1. The instructions that you have shown do not mention "task2" or "task3".

2. Your latest code prints three arguments (on lines 28-33) whether they exist or not.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main( int argc, char *argv[] ) {
  int pos = 1;
  while ( pos < argc ) {
    // do something with  argv[pos]
    // for example:
    std::cout << "Argument " << pos << ": " << argv[pos] << '\n';

    ++pos;
  }
}
Last edited on
I'd make the counting a separate method in whichever loop style you prefer. I guess we're pretending built-in character count methods do not exist ;D

I added some setw(...) which sets the width of the next item

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
#include <iostream>
#include <iomanip>

using namespace std;

int Count(char* arg)
{
    int count = 0;
    int i = 0;
    while (arg[i++] != '\0')
    {
        count++;
    }
    return count;
}
 
int main(int argc, char* argv[])
{
    // We want at least two args.
    // Remember argv[0] is the name of the program itself; 
    //   actual args start at index 1.
    if (argc < 3)
    {
        cout << "Provide at least two arguments to the program.\n";
        return -1;
    }
    
    cout << setw(5) << "#" << setw(8) << "length" << "   arg\n\n";
    for (int i=0; i<argc; ++i)
    {
        cout << setw(5) << i << setw(8) << Count(argv[i]) 
             << "   " << argv[i] << '\n';
    }
    
    return 0;
}


Found an online compiler with actual command-line args (as opposed to cin input): can test this at https://onlinegdb.com/HkHcp4PHm

example output:
    #  length   arg

    0      11   /home/a.out
    1       5   Hello
    2       8   World!!!
    3       6   123.45
Last edited on
Topic archived. No new replies allowed.