Reading integers into a ADT from stdin - c

This is my abstract data structure
typedef struct {
int *items;
int size;
} List;
I would like the user to enter integers on a single line such as
a.out
12 14 2 8 9
and read them into the List. I understand how to add to a list, i guess the thing i don't get is getting the integers from a single line input
Edit: Sorry but I meant using something like scanf not with command line arguments

1. Definition of your main should be int main(int argc,char **argv)
2. The numbers will command line arguments (check value of argc greater than 1 before using argv ).
3. argv[1] , argv[2] will have these numbers , but as string .
4. Convert these to integers using atoi or sscanf functions and store in structure members as you desire.
EDIT
Edit: Sorry but I meant using something like scanf not with command line arguments
You can use fgets , tokenize string using strtok and then convert and store into integer variable.

You have to use input arguments like:
Your main function will look like: int main (int argc, char *argv[] )
In this case you can add your argument at command line as you would
./a.out 12 14 2 8 9
And you can access those argument by argv[1], argv[2], argv[3], ...
and you can loop over the number of arguments the user provided which is contained in the argc variable
example to access the first argument:
int i;
i= atoi(argv[1]);

Related

Pass argument to main function with command line but the value is always 2

This is my main function code
os2.c
#include <stdio.h>
int main( int argc, char *argv[]){
int item;
item = argc;
printf("%d", item);
return 0;
}
I run the following command line in Ubuntu's terminal
gcc -o test os2.c
./test 5
The result printed is equal to 2 instead of 5, What's wrong with my code?
First, your question is not just for Ubuntu/Linux.
It works in Windows and Macintosh too including every OS using the terminal.
argc = argument count: the number of argument that are passed to a program
argv = argument vector: passed arguments
argc is an int that count the arguments of your command line.
I run the following command line in Ubuntu's terminal: gcc -o test os2.c
./test 5
Here your arguments are
argv[0] == ./test
argv[1] == 5
So we conclude that:
argc is 2 based on the number of arguments above.
argv contains the arguments that we've passed to the program.
This is an example of how you use arguments in the right way:
source.c
#include <stdio.h>
int main(int argc, char **argv){
for(int i = 0;i < argc;i++)
printf("arg %d : %s\n",i,argv[i]);
return 0;
}
Command Line
gcc -o test source.c
./test this is a test
Output
arg 0 : ./test
arg 1 : this
arg 2 : is
arg 3 : a
arg 4 : test
But anyways, I recommend to never use the first argument; It'd be a gap in your software cause it can be hacked easily. There're many ways to do whatever you want in C.
Now; You should know what you've to do if you want to get the value 5 instead of counting the number of arguments that you've passed to your application which in the OP case were 2.
argc means the number of argument that are passed to the program. not printed which value you have passed.
Use argv[1] to print value of 5.
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc >= 2)
printf("%d\n", atoi(argv[1]));
return(0);
}
argc (argument count) and argv (argument vector) are how command line arguments are passed to main() in C and C++.
argc is number of arguments passed to program (number of strings pointed to by argv), which is correct in your case. First string is program name, second string is "5" (so you have to convert "5" to int).
This might be a useful reading for you.
If you want to convert second argument to int try this
if (argc < 2)
{
return -1;
}
int item = atoi(argv[1]);
atoi may lead to undefined behavior so you should use strtol instead.
Or you may loop through all arguments
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
// You may print them
printf("%s", argv[i]);
// Convert them, ...
}
Nothing wrong with code. You are passing two arguments ./test and 5. So it shows 2. It is the number of arguments passed to the program.
argc : argument count.
To get the argument passed you can do this.
printf("%s",argv[1]);
In general you check it like this:
if(argc!=2)
{
printf("Usage: ./program-name argument\n");
return EXIT_FAILURE; // failure-considering you are writing this in main.
}
// do your work here.
But in argv[1] you will get the char string. To get an integer out of it, you have to convert it using something like atoi or your custom conversion function. Also you can use strtol() which is useful in conversion from string to long.
1. In case of main return EXIT_FAILURE works but not in other functions but exit(EXIT_FAILURE) works in all the functions
argc is the count of arguments, which is 2 here. If you intend to print 5, you need to print argv[1] (or if you always want the last argument, argv[argc-1]) instead.

Segmentation fault in C associated with array and printing array in correct way

I want to implement this
ls -l | myprogram.
Myprogram takes output of pipe as an input and get every word into array.
then I print out array line by line so that in each line 8 words.
I wrote a code but it gives segmentation fault and does not print my array of of words. What is wrong here? Beginner here....
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){
int result,i;
int j=0;
char string[80];
char wordArray [80];
do {
result=scanf("%s",string);
strcpy(wordArray[j], string);
printf("%s\n", wordArray[j]);
j++;
}
while (result!=EOF);
for (i=0; i<7;i++){
printf("%s ",wordArray[i]);
}
return 0;
}
At least this function call is invalid
strcpy(wordArray[j], string);
Argument wordArray[j] has type char while the first parameter of the function has type char *
You have to define an array of arrays of characters. For example
char wordArray[7][80];
provided that the number of entered strings does not exceed 7.
Take into account that the second loop should look like
for ( i = 0; i < j; i++ ){
Also the first loop is invalid because though the result in the last iteration of the loop is equal to EOF nevertheless you try to copy non-entered string string in the array (as the result is equal to EOF then it means that nothing was entered. So the last valid string will be copied twice)
wordArray is only 1 dimension. Try adding [8][80]
http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm

C – Passing a variable amount of arguments to main

I’m not sure if this is the correct way to do this. See my code below.
I want to be able to pass a list of arguments to main, which would then get stored in another array.
So, I want to be about to start the program with at least 1 argument… or as many arguments as I like. I might set a max amount of arguments to 32.
Eg.
./foo 3
Or
./foo 3 56 12 34 56 111 2222 33
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int numbersEntered[argc];
if (argc <= 1){
printf("Not enough arguments entered\n");
exit(1);
}
printf("Arg count %i\n",argc-1);
for (i=1;i<argc;i++)
numbersEntered[i]=atoi(argv[i]);
for (i=1;i<argc;i++)
printf(" numbersEntered %i\n", numbersEntered[i]);
}
That is already the case, argv is an array of pointers, one pointer for each argument on the command line (plus two, actually, the first one is the name of the program, then the arguments, and then a terminating NULL-pointer).
Regarding the array, the problem is that traditional C requires a size that is known at compile time, you can't just use argc; that said, some compilers like GCC, and more recent C standards, do allow it.

Unexpected output when printing element of array in c

I am creating a simple c program and output of below program should be 2 but i am getting 50 dont know why (i am newbie to c) please let me know where i am missing
#include<stdio.h>
int main(int argc, char** argv) {
int a[4]={'1','2','2','\0'};
printf("The value of a is %d",a[1]);
return 0;
}
here is live output
You initialised the array using ascii character codes. '2' has integer value 50.
Initialise the array as
int a[4]={1,2,2,0};
if you want it to contain integers 1,2,2,0. Or
#include<stdio.h>
int main(int argc, char** argv) {
char a[4]="121";
printf("The value of a is %c",a[1]);
return 0;
}
if you want an array of characters that can be treated as a string. (Note the use of the %c format specifier here.)
50 is the ASCII code of '2'.
Replace '2' with 2 if you want it fixed.
When using character literals like '2' C actually thinks of them as integer types. When you print it using %d format specifier you're telling C to print the value as integer.
If you want to keep the array elements like this: '2', you'll need to change printf format to %c to get a 2 in the console.
When you wrote int a[4]={'1','2','2','\0'}; you actually initialized the array with ASCII Codes of the numbers 1 and 2.
This is because you enclosed them within single quotes thus making them characters instead of integers.
Hence the array actually takes the values int a[4]={49,50,50,0};
To rectify it, you should write the integers without the quotes:
int a[4]={1,2,2,0};
Also note that integer arrays don't need to end with '\0'. That is only for character arrays.
This line
int a[4]={'1','2','2','\0'};
tells the compiler to create an integer array of length 4 and put into it the integers from the curled braces from the right.
Characters in C are 1-byte integers, 1 is a character of 1 and it means integer value of it's ASCII code, i.e. 50. So the first element of an array gets the value of 50.
To fix you should write
int a[4]={1,2,2,0};
remember, that 0 cannot serve as an array end marker, since it is just a number.
If you suppose to get 122 output then do
char a[4]={'1','2','2','\0'};
printf("The value of a is %s",a);
since strings in C are character arrays with 0 as termination symbol.
Also you can let compiler to count values for you
char a[]={'1','2','2','\0'};
You are assigning chars not integers:
note
'2' means char use %c
2 manes int use %d
"2" means string. use %s
all are different:
in your code you can do like to print 2:
int main(int argc, char** argv) {
char a[4]={'1','2','2','\0'};
printf("The value of a is %c",a[1]);
return 0;
}

How to read in numbers as command arguments?

How can make it where the program reads any two integers input before the program is run?
I want the output to look like this, with x and y being any variables typed in (I am using Cygwin):
$ ./a x y
product of x and y
sum of x and y
I used int main(int argc, char *argv[]). I tried to assign argv[2] to x and argv[3] to y, but when I compile the program it says assignment makes integer from pointer without cast. What does this mean and how do I fix it?
Assuming the C language:
Command line arguments are found in the argv array - argv[1], argv[2] etc.
Converting a string argument to an integer can be done with the atoi function.
Output can be done with the printf function.
[Trying to teach you to fish, rather than providing a fish. Good luck!]
Assuming that you are using bash, you can use $1, $2, etc for those arguments. If, however, you are useing C, you're code should looks something more like this:
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[]) {
if(argc<=1) {
printf("You did not feed me arguments, I will die now :( ...");
exit(1);
} //otherwise continue on our merry way....
int arg1 = atoi(argv[1]); //argv[0] is the program name
//atoi = ascii to int
//Lets get a-crackin!
}
Hope this helps.
Firstly, if you run your C program as
./a x y
then a is argv[0], x is argv[1], and y is argv[2], since C arrays are 0 based (i.e. the first item in the array is indexed with 0.
Realize that argv is an array (or I've always thought of it as an ARGument Vector, though you might think of it as an array of ARGument Values) of character string pointers. So, you need to convert the strings to integers. Fortunately, C has library functions to convert ASCII to integer. Look at the stdlib.h documentation.
Good luck!
My code would look like this.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments
int total = 0;
int i;
char *value;
for(i = 1; i < argc; i++)
{
// The integers given is read as (char *)
value = argv[i];
printf("Command line index: %d value: %s in ascii: %d\n", i, value, *value);
// Convert ascii to integer.
// atoi function is defined in stdlib.h
total += atoi(value);
}
// .2f limits the decimals to two digits after '.'
printf("Total of given integers is %d\n", total);
}
int arg1 = argv[1];
Will not work because it is an array of pointers which holds all the addresses of argv[0]....argv[n] to get the value of argv[..] suppose argv[1] you have to write:
int n=*argv[1]-'0'; // Direct atoi
Simply using atoi() will convert the char type console input into int
int main(argc, char* argv[])
{
int first = atoi(argv[1]);
printf("%i", first);
}
If you ask why argv[1] instead argv[0], the answer is the first ever argument is the name of your executable file ./some 2 int this case argv[0] will point to 'some'.
In command line arguments, char*argv[] is string type. We need to convert it into integers. We do this by type casting but in oop we do this by the atoi function(method), it works like typecasting(means method of convert one data type to other)

Resources