Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read Input Into Array

Status
Not open for further replies.

eb24

Programmer
Dec 17, 2003
240
US
It's been a super long time since I've gone down to a language like C (do .NET these days) and would really appreciate some assistance:

How can I input data at the command prompt and then parse out the strings with only using the <stdio.h> library and such string functions like strtok?

Code:
Input: This is just a test
Code:
Output:
This
is
just 
a
test
 
Code:
#include <stdio.h>
int main( int argc, char *argv[] ) {

	if( argc == 0 ) {
		puts( "No command line available." );
	} else {
	
		printf( "The program now running: %s\n", argv[0]);
		if ( argc == 1 ) {
			puts( "No arguements received on the command line." );
		} else {
	
			puts( "The command line arguements:" );
			int x;
			for( x = 1; x < argc; x++ ) {
				puts( argv[x] );
			}
	
		}

	}

}

This is taken from 'C in a Nutshell' - it uses only the stdio.h

Basically, to explain it there are two variables received in the function main();
argc is the number of arguements received on the command line.
argv[] stores these string command line input.

Basically, firstly argc will equal 1 if one command line option is entered - such as '<program_name> "This is test"'

But, remember, the first cell in the array is the name of the program, if the o/s does not send the name of the program, argv[0] is blank or <program_name>

There fore, command lines options start at argv[1] until argv[argv -1] (-1 because the last array cell in argv containts a null pointer)

Regards,

Alexander
 
Sorry, argc will equal TWO if a command line parameter was passed to the program.
 
GoAskAlice:

Wow! This is exactly what I am looking for! Thank you so much for your expeditious response!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top