how do i save int argc, char* argv in to int someting.
i am trying to get the arguments from a test program and save it into int ****;
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
int limit = argc;
cout<< limit <<endl;
for (int candidate = 2; candidate < limit; candidate++) {
int total = 1;
for (int factor = 2; factor * factor < candidate; factor++) {
if (candidate % factor == 0)
total += factor + candidate / factor;
}
if (total == candidate) {
cout << candidate << ' ';
}
}
return 0;
}
and the program is pre-set the arguments is 100, and it just can't save in to int limit
Something like this
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Not enough arguments\n";
return -1;
}
int limit = atoi(argv[1]); // convert first argument to integer
...
Related
i want to create a link between two programs throughout the execs functions .
my idea is to create function then point on it by a function pointer then send it to the other program to test it . this is my first programenter code here
1- is this possible ?
2- how ?
i get this idea because i find each time to change the function name in the main function but the remainning still as it was but if i send a pointer function as a character pointer then my programm still as it without changing
#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void
Random(int* ,const int );
int*
selection_sort(int *arr ,const int length)
{
int i = 0,minIndex{0},tmp{0},k{0};
while(i < length-1) // T(n-1) * C1
{
minIndex = i; // Tn * C2
for(int j = i+1 ; j < length ; j++ ) // som(Ti) from i = 0 to i = length-1 )*C3.
{
if((arr)[j] < (arr)[minIndex])
minIndex = j;
}
if(minIndex != i) // Tn * C4
{
tmp = (arr)[i];
(arr)[i] = (arr)[minIndex];
(arr)[minIndex] = tmp;
}
i++;
}
return arr;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i{-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}
int main(int argc,char* argv[])
{
int* (*ptr)(int*,const int ) = selection_sort;
execl("/home/hellios/Documents/Algorithms/sort_Algorithms/main",(char*)ptr,0); // complete the call
return EXIT_SUCCESS;
}
sort_Algorithms/main.c
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
void
Random(int* array,const int length);
int
main(int argc,char* argv[])
{
int* (*ptr)(int *,const int ) =(int* (*) (int*,const int)) argv[1];
int arr1[100],k{0},*arr;
Random(arr1,100);
arr = (*ptr)(arr1,100);
//selection_sort(arr,100);
cout<<"out of selection_sort"<<endl;
for(int j = 0 ; j < 100 ; j++ )
{
printf("[%d]\t", arr[j]);
if(!(++k %10))
cout<<endl;
}
printf("\n");
return EXIT_SUCCESS ;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i {-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}
Here is my program
#include <bits/stdc++.h>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to find gcd of input2ay of
// numbers
int findGCD(int input2[], int n)
{
int result = input2[0];
for (int i = 1; i < n; i++)
{
result = gcd(input2[i], result);
if(result == 1)
{
return 1;
}
}
return result;
}
// Driver code
int main(int input1,int input2[40])
{
int n = sizeof(input2) / sizeof(input2[0]);
cout << findGCD(input2, n) << endl;
return 0;
}
The input has to go in following format
3 2 4 8
where 3 is size of array and 2 4 8 are elements of array.
Now I am getting following errors
main.cpp:40:5: warning: second argument of ‘int main(int, int*)’ should be ‘char **’ [-Wmain]
int main(int input1,int input2[40])
^~~~
main.cpp: In function ‘int main(int, int*)’:
main.cpp:43:23: warning: ‘sizeof’ on array function parameter ‘input2’ will return size of ‘int*’ [-Wsizeof-array-argument]
int n = sizeof(input2) / sizeof(input2[0]);
^
main.cpp:40:34: note: declared here
int main(int input1,int input2[40])
^
What is the problem here?
my question is mostly code adding more details.
edit
based on suggestions I came up with using atoi.
#include <stdio.h>
unsigned gcd(unsigned x, unsigned y){
unsigned wk;
if(x<y){ wk=x;x=y;y=wk; }
while(y){
wk = x%y;
x=y;
y=wk;
}
return x;
}
int gcd_a(int n, int a[n]){
if(n==1) return a[0];
if(n==2) return gcd(a[0], a[1]);
int h = n / 2;
return gcd(gcd_a(h, &a[0]), gcd_a(n - h, &a[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,input1;
int *value;
for(i = 1; i < argc; i++)
{
// The integers given is read as (char *)
value[i] = atoi(argv[i]);
total++;
}
input1 = total;
int gcd = gcd_a(input1, value);
printf("%d\n", gcd);
return 0;
}
But still this is not giving me desired result.
I compiled it online but it did not give any error but it did not took any arguments also.
The post can not be submitted because it looks mostly code java script programming error in SO.
The main method declaration must be int main(int ,char**);
Here you will get array of c-strings. i.e (["10","20","40"....]).
So you need to convert char* to integer using below methods
using atoi() method ==> read this
sscanf() method ==> read this
see the below code
int findGCD(char* input2[], int n)
{
int result = atoi(input2[1]); /*Here first argument is fileName itself ,so we are taking from second.i.e input2[1]*/
for (int i = 2; i < n; i++)
{
int a = atoi(input2[i]);
result = gcd(a, result);
if(result == 1)
{
return 1;
}
}
return result;
}
// Driver code
int main(int args,char** argv)
{
// for(int i = 0;i < args;i++)
// {
// cout <<"argv["<<i<<"] = "<<argv[i]<<endl;
// }
cout << "GCD::"<<findGCD(argv, args) << endl;
return 0;
}
I am a newbie to C++ and I've tried to write a simple string reverse program. When I compile it, everything is OK, but when I run it, I get the following error:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted (core dumped)
What I am doing wrong? Here is my code.
#include <iostream>
using namespace std;
string reverse_string(char* argv[], int i);
int main(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
cout << reverse_string(argv, i) << endl;
}
return 0;
}
string reverse_string(char* argv[], int i)
{
string arg = argv[i + 1];
string output;
int length = arg.length();
for (int index = 1; index <= length; index++)
{
output += arg[length-index];
}
return output;
}
This: argv[i + 1] in the construction of your reversed string should be argv[i] and the main loop should be for (i=1; i<argc; ++i)
And there are simpler ways to reverse a string:
std::string reverse_string(char* argv[], int i)
{
std::string arg = argv[i];
return std::string(arg.rbegin(), arg.rend());
}
This error message
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
means that you are trying to call constructor of std::string passing as argument pointer NULL. The problem is that *(argv + argc) is NULL pointer.
Also take into account that you must include header <string>
As for the reverse function then it can be written much simpler then that of you. First of all it could have only one parameter of type const char *
For example
#include <iostream>
#include <string>
std::string reverse_string( const char* s );
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
std::cout << argv[i] << " -> " << reverse_string( argv[i] ) << std::endl;
}
return 0;
}
std::string reverse_string( const char* s )
{
std::string arg( s );
return std::string( arg.rbegin(), arg.rend() );
}
Ok thanks for help everyone! I just didn't want to reverse argument 0, which is program's name. But I found another way around it. If anyone is interested, here is the fixed code:
#include <iostream>
using namespace std;
string reverse_string(char* argv[], int i);
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
cout << argv[i] << " -> " << reverse_string(argv, i) << endl;
}
return 0;
}
string reverse_string(char* argv[], int i)
{
string arg = argv[i];
string output;
int length = arg.length();
for (int index = 1; index <= length; index++)
{
output += arg[length-index];
}
return output;
}
I'm making a simple script that generates 8 random values from 0 to 7 and stores them into an array named random_numbers.
This is my try:
int main(int argc, char** argv) {
int random_numbers[8];
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] = 1+ rand() % 8;
cout << random_numbers[i] << endl;
}
return 0;
}
This gives me repeated values. I would like to have random_numbers filled of random values from 0 to 7, but without any repeated numbers.
How can I do that?
Generate the numbers 0 through 7, then shuffle them. Assuming this is actually C++, not C (because of the cout), use std::random_shuffle:
#include <algorithm>
#include <cstdlib>
#include <iostream>
int main()
{
int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
std::srand(unsigned(std::time(0)));
std::random_shuffle(a, a + 8);
for (int i=0; i<8; i++)
std::cout << a[i] << " ";
std::cout << std::endl;
}
Be warned: cppreference.com states that "The random number generator is implementation-defined, but the function std::rand is often used." I've seeded that with std::srand, but apparently that's not completely portable.
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
class Random {
public:
Random(){
srand( static_cast<unsigned int>(time(NULL)));
}
unsigned int operator()(unsigned int max){
double tmp = static_cast<double>( rand() ) / static_cast<double>( RAND_MAX );
return static_cast<unsigned int>( tmp * max );
}
};
int main(int argc, char** argv) {
int random_numbers[8];
int size = sizeof(random_numbers)/sizeof(int);
for(int i=0;i<size;++i)
random_numbers[i]=i;
Random r;
random_shuffle(random_numbers, random_numbers + size, r);
for (int i = 0; i < 8; i++) {
cout << random_numbers[i] << endl;
}
return 0;
}
Since you are using c++ any way I modified you code a bit more. Use vector instead of array, this should make your life easier, and this generates 0-7 in a random order without duplicates:
compile with -std=c++0x
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
int main(int argc, char** argv) {
srand(time(NULL));
vector<int> random_numbers(8);
iota(random_numbers.begin(), random_numbers.end(), 1);
random_shuffle(random_numbers.begin(), random_numbers.end());
for (unsigned i = 0; i < random_numbers.size(); i++) {
cout << random_numbers[i] << endl;
}
return 0;
}
try this code:
int random_numbers[8];
int main(int argc, char** argv) {
srand((unsigned)time(NULL));
for (int i = 0; i < 8; i++) {
random_numbers[i] =getRand(i);
cout << random_numbers[i] << endl;
}
return 0;
}
int getRand(int entries)
{
int flag = 0;
int randno ;
randno = rand() % 8;
for(int i=0;i<entries;i++)
{
if( random_numbers[i]==randno)
{
randno = rand() % 8;
continue;
}
}
return randno;
}
I currently have this function to print out every rows of my tables
static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
for(int i = 0; i < argc; i++)
{
cout.width(17); cout << left << argv[i];
}
std::cout << "\n";
return 0;
}
How do I print out szColName, such that it only appear once on top, and not multiple occurences of it?
Tried this:
static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
int n = sizeof(szColName) / sizeof(szColName[0]);
for (int i = 0; i < n; i++)
{
cout.width(17); cout << left << szColName[i];
}
printf("\n");
for(int i = 0; i < argc; i++)
{
cout.width(17); cout << left << argv[i];
}
std::cout << "\n";
return 0;
}
But it outputs everytime after a outputting the row values
You might want to declare a static bool inside callback to record whether it has already printed out the column names. Or, if you want to be able to reset it...
such as:
static bool firstline = true;
static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
if (firstline){
int n = sizeof(szColName) / sizeof(szColName[0]);//this is incorrect but fixing
// it requires changing the prototype.
//See the comments below
for (int i = 0; i < n; i++)
{
cout.width(17); cout << szColName[i] << left;
}
printf("\n");
firstline=false;
}
for(int i = 0; i < argc; i++)
{
cout.width(17); cout << argv[i] << left;
}
std::cout << "\n";
return 0;
}
int main(){
for(int x=0;x<10;++x)callback( ... , ... , ... ); // give whatever argument you need to give
firstline = true; //reset the variable so that next time you call it, the col names will appear
for(int x=0;x<10;++x)callback(...,...,...);// now the col names will appear again.
}
I assume that what you provide would print out the rows and the column names correctly. I only added a variable to check if printing column names are needed.