I am having some trouble having the get opt to identify the flag regardless of what position it's called at in the inputs in. My program takes in 4 inputs as parameters for the program to function.
here is my code
int a= strtol(argv[1],NULL,10);
int b = strtol(argv[2],NULL,10);
double c = strtol(argv[3],NULL,10);
double d = strtol(argv[4],NULL,10);
so for example i would run my program by calling ./test 5 5 5 5
However I need the program to recognize it regardless of position and then set the variables according to where it is positioned at. Currently I am trying to have it figure out when -p(number) is passed in. So for example ./test 5 5 5 5 -p5 or ./test p 5 5 5 5 5 it will recognize the 5 next to the p up to 1 space away and store that number
my getopt that i have right now is as follows
int i ;
int j = 0;
while ( (opt = getopt(argc,argv, "p:") ) != 1){
switch(opt){
case 'p':
cycles = (int) strtol ( optarg, Null,10);
Related
I am new to C and need some help with this basic program. I want the program to print out the sum directly after the input. I tried to put printf("..%d", sum); inside the for brackets and got but program shuts after the first input. It works if I have a scanf("%d", &value); before the For and inside the for brackets but there for I don't get the format I want.
I want the values to be printed vertical, left side should be inputs and right side should be output as u can see in the image.
Here is my code
#include <stdio.h>
int main()
{
int sum = 0, c, value;
scanf("%d", &value);
for (c = 1; c <= value; c++)
{
sum = sum + c;
printf("..%d", sum);
scanf("%d", &value);
}
return 0;
}
It appears you are a bit confused about which values you are actually summing (or I am...) From your problem descriptions (and from how you have initialized your for loop), it appears you are to input the ending value and then are to sum from 1 to that value?
If that is the case, there is no need for additional input within the for loop, your loop variable provides all values you are supposed to add to your sum.
Additionally, you cannot use any user-input function correctly unless you validate the return to determine whether input succeeded or failed.
Putting it altogether, you could do:
#include <stdio.h>
int main()
{
int sum = 0, c, value;
fputs ("sum from 1 to: ", stdout); /* prompt for input */
if (scanf ("%d", &value) != 1 || value < 1) { /* VALIDATE EVERY INPUT !!! */
fputs (" error: invalid integer input or negative value.\n", stderr);
return 1;
}
putchar ('\n'); /* add newline before output */
/* you are looping over the values of c -- no input is necessary */
for (c = 1; c <= value; c++)
{
sum = sum + c; /* sum */
printf ("%2d\t\t\t%d\n", c, sum); /* output value added and sum */
}
return 0;
}
Example Use/Output
$ ./bin/suminput
sum from 1 to: 5
1 1
2 3
3 6
4 10
5 15
Or for 1-10:
$ ./bin/suminput
sum from 1 to: 10
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
Or if invalid input is provided:
$ ./bin/suminput
sum from 1 to: twenty
error: invalid integer input or negative value.
Or a negative value:
$ ./bin/suminput
sum from 1 to: -10
error: invalid integer input or negative value.
No harm done.
Taking Input For The Sum
The other way I read your sample input and output (characterized by the 0 ending the loop), is that your task is simply to read inputs and sum them until the user enters 0 (or an invalid integer) displaying the sum after each input. That is quite a bit easier -- but the requirement to validate each input remains the same, e.g.
#include <stdio.h>
int main()
{
int sum = 0, value;
while (scanf ("%d", &value) == 1 && value != 0) { /* input value */
sum += value; /* sum */
printf ("%20d\n", sum); /* output sum */
}
}
Example Use/Output
$ ./bin/suminput2
1
1
2
3
3
6
4
10
5
15
0
Or any random values until 0 is entered:
$ ./bin/suminput2
1
1
-2
-1
3
2
-4
-2
5
3
-6
-3
0
(note: there are ways to place the input and output on the same line but that differs between compilers and operating systems. Windows could use the non-standard getch(), while on Linux you would need to do the same thing by changing input to non-cannonical mode with tcsetattr(). Another way would simply be to save the inputs until the user enters 0 and then to loop over all values input summing and displaying the values (though that would eliminate the 0 at the end of input show in your example input))
Look things over and let me know if you have further questions (and also whether I interpreted your question correctly). If you do need to enter each value to sum, let me know and I am happy to help further.
I am supposed to write a program that "quicksort"s a given array of numbers. The problem is , dynamic memory allocation is not allowed and nor am I given the number of "numbers" that are supposed to be inputs of my program.
For instance, here's an input/output example:
INPUT: 0 1 5 3 6 2 4
OUTPUT: 0 1 2 3 4 5 6
But I just can't seem to be able to close my while loop when getting the numbers using scanf(); (I know , scanf() is silly , but I can't use "iostream" either)
Here's the code I was trying to get to work:
int main()
{
int target_arr[1000], l, h, i = 0, c = 0, k = 0;
while (scanf("%d", &target_arr[i]) != EOF)
{
i++;
}
h = i -1;
l = 0;
quick(l, h, target_arr);
print_arr(target_arr, i );
return 0;
}
quick() and print_arr() functions are previously defined and work perfectly well given the proper input.I just don't know how to stop the loop when I'm done inputting.
Any help would be greatly appreciated.
This question already has answers here:
How to read the standard input into string variable until EOF in C?
(5 answers)
Closed 9 years ago.
I have this graph (with the first line is number of vertices, the following lines are directed edges):
9
1 4
1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9
There is no information to know how many edges are in the input so can anyone suggest a way to read this kind of input?
Thank you you all,
I finally solved it, here is the input code:
while (1) {
tmp1 = scanf("%d", &x);
if (tmp1 == -1) // fix here
break;
tmp2 = scanf("%d", &y);
new_vertex = (Vertex *) malloc(sizeof(Vertex));
new_vertex->adj_vertex = NULL;
new_vertex->vertex_no = y;
new_vertex->time_stamp_visit = 0;
new_vertex->time_stamp_finish = 0;
last_vertex = getLastVertex((graph+x));
last_vertex->adj_vertex = new_vertex;
}
Loop over this list from 1 to n-1 read the pair and insert the edge between these two nodes in your graph data structure.
I advise reading this: http://shygypsy.com/iotutorial.html
And using the method under "Read integers, one at a time, skipping whitespace, until the end of input."
In your code maintain state on whether it's a beginning or a ending vertice being inputted.
Don't forget to press ctrl+d when done typing input.
You can use a "termination character" that counts as EOF, like a -1 or something after the last pair of nodes.
Then your data would be:
9
1 4
1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9
-1
And your code:
while(1){
scanf("%d %d", &num1, &num2);
if(num1==-1) break;
// process
}
I wrote getnum() to return an integer from stdin:
int getnum(int * last) {
int c, n = 0;
while ((c = getchar()) != EOF && 0x30 <= c && c < 0x40)
n = n * 10 + (c - 0x30);
if (last)
*last = c;
return n;
}
It will get digits from stdin until a non-digit character is retrieved. Because getnum() doesn't care what the non-digit character is, it doesn't matter how the numbers are arranged. They could all be on the same line, or in space-delimited pairs, one per line. I put this in a loop that stops once it reads in the right number of numbers, but you could easily loop until last pointed to non-whitespace.
Additionally, if you want to read from a FILE or fd (integer file descriptor), pass the FILE/fd to getnum() and use getc(FILE *)/fgetc(int).
The output of the program below is 6. I am not able to figure out why. When I trace it out by hand, I am getting 5.
#include<stdio.h>
#include<conio.h>
main()
{
int i,count=0;
char *p1="abcdefghij";
char *p2="alcmenfoip";
for(i=0;i<=strlen(p1);i++) {
if(*p1++ == *p2++)
count+=5;
else
count-=3;
}
printf("count=%d",count);
}
if(*p1++ == *p2++) is reading both p1 and p2 character by character. When the characters are the same, it will increase count by 5, else it will decrement it by 3. But, there is another thing that you didn't pay attention to: strlen(p1) will always be different in each iteration, because p1 will change. So, in each iteration, you also need to check its value.
p1 p2 count i strlen (before entering into the loop body)
a a 5 0 10
b l 2 1 9
c c 7 2 8
d m 4 3 7
e e 9 4 6
f n 6 5 5 <- No more - this is the last one
The trick here is, strlen(p1) changes every iteration. So loop condition goes
0 <= 10 +5
1 <= 9 -3
2 <= 8 +5
3 <= 7 -3
4 <= 6 +5
5 <= 5 -3
So equal characters are a, c, e, shown as +5 above. Total is 6.
Your program stops when i>strlen(p1) because you are changing p1 each time you do *p1++.
When it computes the condition strlen returns the size from the las char.
If you store the value in a variable at the beginning (before your loop) it should work.
Anyway, try to avoid pointer arithmetic...
I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn't get it really:
#include<stdio.h>
void count(int);
int main()
{
int x=10,z;
count(x);
}
void count(int m)
{
if(m>0)
count(m-1);
printf("%d",m);
}
When the 1st time count is called with argument as 10. it fulfills the condition and then here starts the recursive part. what happens really when a function calls itself? I don't get it. Please explain with reference to stacks.
While m is greater than 0, we call count. Here is a representation of the stack calls:
count (m = 10)
count (m = 9)
count (m = 8)
count (m = 7)
count (m = 6)
count (m = 5)
count (m = 4)
count (m = 3)
count (m = 2)
count (m = 1)
count (m = 0)
printf 0
printf 1
printf 2
printf 3
printf 4
printf 5
printf 6
printf 7
printf 8
printf 9
printf 10
next time it calls itself it has a smaller value
count(int m)
{
if(m>0)
count(m-1); // now it is calling the method "count" again, except m is one less
printf("%d",m);
}
So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:
if(m>0)
What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)
so you have:
count(int m)
{
if(m>0)
{
count(m-1); // now it is calling the method "count" again, except m is one less
}
printf("%d",m);
}
So, the recursive calls will stop once m is not > 0, and then it will call the printf.
After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....
So the output should be:
"0 1 2 3 4 5 6 7 8 9 10"
EDIT:
In terms of a stack:
This is what the stack is doing:
count(10) // push count(10)
->
count(9) // push count(9)
count (10)
->
...
->
count(0) // push count(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
-> (and then it starts printing and popping the method off the stack)
// pop count(0), and printf(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
// pop count(1), and printf(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
...
->
// pop count(9), and printf(9)
count(10)
->
// pop count(10), and printf(10)
When a function is called the return address (of the next code to execute) is stored on the stack along with its current arguments. Once the function finishes the address and arguments are popped so the cpu will know where to continue its code execution.
Let's write the addresses of the function (for the purpose of this example only)
count(int m)
{
(address = 100) if(m>0)
(address = 101) count(m-1); // now it is calling the method "count" again, except m is one less
(address = 102) printf("%d",m);
}
For m = 1:
The if is fullfield so we execute code at address 101 with m = 1. address 102 and m = 1 are pushed to the stack and the function is executed again from address 100 with m = 0. Since m = 0 we execute address 102 and printing 0 on console. The function ends and the last return address (102) and argument m = 1 are popped and the line at address 102 is executed printing 1 on the screen.
The function count is called with an integer argument of 10.
Since the function argument m which is 10 is greater than 0 the function count calls itself with an integer argument of m which is 10 minus 1 which equals 9.
Step 2 repeats with varying arguments (m-1) until m is not greater than 0 and which point the program prints the value of m.
The recursive function just modifies the parameter given to it and calls itself with that modified value until the desired result is returned (in this case m not being greater than 0).
Each number refers to the line number.
#include<stdio.h>
count(int);
main()
{
1int x=10,z;
2count(x);
}
count(int m)
{
3if(m>0)
4 count(m-1);
5printf("%d",m);
}
The execution happens like this(with x=3) -
line number|value of x
1 3
2 3
3 3
4 2
3 2
4 1
3 1
4 0
5 0
5 1
5 2
5 3
Numbers printed on the screen 0 1 2 3
If you want a more specific answer, then you have to look into how compilers work. But generally speaking the compiler will create machine code for the function that includes a preamble, in this code enough memory is allocated on the stack (by decrementing a stack pointer) that a copy of the functions variables can be placed on the stack (we can store the state of the function).
The function will have values stored in registers and memory and these must be stored on the stack for each (recursive) call, otherwise the new call will overwrite the precious data!. So very basically the machine code looks like this (pseudo code)
//store m on the stack
store m,stack_pntr+m_offset
//put input values in designated register
a0 = m
//allocate memory on the stack
stackPntr -= stack_size_of(count_vars)
//store return address in allocated register
//jump to the first instruction of count
.
.
By changing some data used for computation we can go back and read the same instructions again and get a different result. The abstraction of recursive function allows us to manipulate the data we want to change in a nice "call by value" way so that we don't overwrite it unintentionally.
This is done by the compiler when it stores the state of the calling function on the stack so we don't have to manually store it.