Hello, I am a beginner in C language and I have a question.
I have to write a function to calculate the max. elements of numbers, which we put in as input arguments. (to convert the string into a number I have to use atoi function. In the main program we have to check how many arguments there are. If input arguments aren't given, the program says "Result 0", else it prints the max. element.
Here's the code I wrote, but it doesn't work so I ask for help,
#include <stdio.h>
using namespace std;
int najvecjiElement (int argc, char *argv[])
{
int maxStevilo = argv[1];
for (int i = 1; i <= argc; i++) {
if (argv[i] > maxStevilo) {
maxStevilo = argv[i]; }
}
return maxStevilo;
}
int main(int argc, int *argv[])
{
int i;
cout << "Najvecje stevilo:" << endl;
cout << najvecjiElement(argc,argv);
hello,I'm a Chinese. my english weak. I think the code will solve your problem. If you want to calculate the length of char *, replace atoi(*(++argv)) ,use strlen(*(++argv)).
Code:
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
using namespace std;
int maxElementsOfNumber(int argc, char* argv[])
{
int m_maxElement = atoi(*(++argv));
if ( argc == 2)
{
return m_maxElement;
}
for (int i = 1; i <= argc-2; i++)
{
int temp_maxElement = atoi(*(++argv));
if ( temp_maxElement > m_maxElement)
{
m_maxElement = temp_maxElement ;
}
}
return m_maxElement;
}
int main(int argc,char* argv[])
{
if (argc < 2)
{
cout << " The element of number is 0" << endl;
return -1;
}
cout << " The max element of number is: " << maxElementsOfNumber(argc,argv) << endl;
}