Ошибка too few arguments to function

Question

I’m fairly new to C and I’ve got this error when I try to compile it (GCC):

error: too few arguments to function `printDay’

My questions are:

  1. What does it mean?
  2. How do I fix this?

P.S this is not my full code, it’s just this error I’m faced with.
Thanks in advance.

Code

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

#define MAX_DAYS 31
#define MIN_DAYS 1
#define MAX_MONTHS 12
#define MIN_MONTHS 1

enum monthsOfYear
{
    jan = 1,
    feb,
    mar,
    apr,
    may,
    jun,
    jul,
    aug,
    sep,
    oct,
    nov,
    dec
};

enum daysOfWeek
{
    sun = 1,
    mon,
    tue,
    wed,
    thu,
    fri,
    sat
};

int input();
void check(int month, int day);
void printDay(int month, int day, int firstDay);

int main()
{
    printf("Hello! Welcome to the day calculator!n");
    printDay(input());
    return (0);
} 

/*this function takes the input from the user
input: none
output: the first day
*/ 
int input()
{
    enum daysOfWeek day = 0;
    enum monthsOfYear month = 0;
    
    int firstDay = 0;
    
    printf("Enter month to check: (1-jan, 2-feb, etc) ");
    scanf("%d", &month);
    printf("Enter day to check: ");
    scanf("%d", &day);
    check(month,day);
    printf("Enter the weekday of the 1st of the month: (1-Sunday, 2-Monday, etc) ");
    scanf("%d", &firstDay);
    
    return firstDay;
}

/*
this function checks the validity of the input
input: day, month
output: none
*/
void check(int month, int day)
{
    if(month > MAX_MONTHS || month < MIN_MONTHS && day > MAX_DAYS || day < MIN_DAYS)
    {
        printf("Invalid input, try againn");
        input();
    }
    if (month == feb && day > 28)
    {
        printf("Invalid input, try againn");
        input();
    }
    if (month == jan && day > 31)
    {
        printf("Invalid input, try againn");
        input();
    }
}

void printDay(int month, int day, int firstDay)
{
    int date = 0;
    date = day - firstDay;
    switch(day)
    {
        case sun:
        printf("%d.%d will be a Sunday", day, month);
        break;
        
        default: 
        break;
    }
}

Home »
C programming language

In this article, we are going to learn about an error which occurs in C programming language when we use less argument while calling a function. If we do this compiler will generate an error «Too few arguments to function».

Submitted by IncludeHelp, on May 15, 2018

Too few arguments to function in C language

This error occurs when numbers of actual and formal arguments are different in the program.

Let’s understand first, what actual and formal arguments are?

Actual arguments are the variables, values which are being passed while calling a function and formal arguments are the temporary variables which we declare while defining a function.

Consider the given example:

int sum(int a, int b, int c)
{
	return  (a+b+c);
}

int main()
{
	int x,y,z;
	x = 10; y = 20; z = 30;
	
	printf("sum = %dn",sum(x, y, z));
	
	return 0;
}

Here, actual arguments are x, y and z. Formal arguments are a, b and c.

When, the error «too few arguments to function is occurred»?

Remember: Number of actual arguments (the arguments which are going to be supplied while calling the function) must equal to number of formal arguments (the arguments which are declared while defining a function).

This error will occur if the number of actual and formal arguments is different.

Consider the above example, and match with these below given calling statements, these statements will generate errors:

printf("sum = %dn", sum(x, y));
printf("sum = %dn", sum(x));
printf("sum = %dn", sum(10, 20));

Example: (by calling functions with less number of arguments)

#include <stdio.h>

int sum(int a, int b, int c)
{
	return  (a+b+c);
}
int main()
{
	int x,y,z;
	x = 10; y = 20; z = 30;
	
	printf("sum = %dn", sum(x, y));
	printf("sum = %dn", sum(x));
	printf("sum = %dn", sum(10, 20));
	
	return 0;
}

Output

prog.c: In function ‘main’:
prog.c:12:23: error: too few arguments to function ‘sum’
  printf("sum = %dn", sum(x, y));
                       ^~~
prog.c:3:5: note: declared here
 int sum(int a, int b, int c)
     ^~~
prog.c:13:23: error: too few arguments to function ‘sum’
  printf("sum = %dn", sum(x));
                       ^~~
prog.c:3:5: note: declared here
 int sum(int a, int b, int c)
     ^~~
prog.c:14:23: error: too few arguments to function ‘sum’
  printf("sum = %dn", sum(10, 20));
                       ^~~
prog.c:3:5: note: declared here
 int sum(int a, int b, int c)
     ^~~
prog.c:9:10: warning: variable ‘z’ set but not used [-Wunused-but-set-variable]
  int x,y,z;
          ^

So, while calling a function, you must check the total number of arguments. So that you can save your time by this type of errors.

Example: (by calling functions with correct number of arguments)

#include <stdio.h>

int sum(int a, int b, int c)
{
	return  (a+b+c);
}
int main()
{
	int x,y,z;
	x = 10; y = 20; z = 30;
	
	printf("sum = %dn", sum(x, y, z));
	printf("sum = %dn", sum(x,y,z));
	printf("sum = %dn", sum(10, 20,30));
	
	return 0;
}

Output

sum = 60
sum = 60
sum = 60

3 / 3 / 0

Регистрация: 19.10.2008

Сообщений: 31

1

02.03.2009, 17:04. Показов 56374. Ответов 9


Студворк — интернет-сервис помощи студентам

Здравствуйте!
Есть программа, которая при компиляции вываливается с ошибкой. Нужно эту ошибку найти.

Код

#include <iostream>
#include <string>

using namespace std;

void func (double cena, double procent, double sum, double procentrub, double procsum) //Функция подсчёта и вывода информации
{ for (int cntr = 1; cena != 0; cntr++)
    { cout << "nВведите цену " << cntr << "-го товара: ";
        cin >> cena;
        if (cena != 0)
        { cout << "Введите скидку " << cntr << "-го товара: ";
            cin >> procent;
            procentrub = (cena / 100) * procent; // Скидка в рублях
            procsum += procentrub;
            sum = sum + (cena - procentrub); } // Цена товара со скидкой
        else
        {    cout << "nИтоговая цена: " << sum << endl; } } }

int main (int argc, char *argv[])
{ func(); }

Вываливается с ошибкой Too few arguments to function ‘void func(double, double, double, double, double)’
Почему так? Почему нельзя засунуть много аргументов? Помогите!



1



176 / 168 / 27

Регистрация: 12.01.2009

Сообщений: 430

02.03.2009, 17:12

2

Можно много.Ты же не одного не передаешь.



1



Почетный модератор

7390 / 2636 / 281

Регистрация: 29.07.2006

Сообщений: 13,696

02.03.2009, 17:13

3

func у тебя параметры принимает, а ты ее как вызываешь, видел?
too few — слишком мало, грамотей, блин



1



Lord_Voodoo

Супер-модератор

8783 / 2536 / 144

Регистрация: 07.03.2007

Сообщений: 11,873

02.03.2009, 17:13

4

ну вообще все правильно вам пишут, и на аргументы вас никто не ограничивает, только у меня вопрос:
если это вызов функции:

C++
1
{ func(); }

, где параметры вообще? или вы рассчитываете, что компилятор сам додумается что-то в функцию передать?

Vourhey, Humanitis, так это вижу не я один… ну повезло… а то думал — переработался)))



1



L@m@kЪ

3 / 3 / 0

Регистрация: 19.10.2008

Сообщений: 31

02.03.2009, 17:23

 [ТС]

5

Цитата
Сообщение от Vourhey
Посмотреть сообщение

func у тебя параметры принимает, а ты ее как вызываешь, видел?
too few — слишком мало, грамотей, блин

Глубоко сожалею о своей тупости и безграмотности, а также о лени поискать в словаре

Добавлено через 1 минуту 53 секунды

Цитата
Сообщение от WooDooMan
Посмотреть сообщение

ну вообще все правильно вам пишут, и на аргументы вас никто не ограничивает, только у меня вопрос:
если это вызов функции:

C++
1
{ func(); }

, где параметры вообще? или вы рассчитываете, что компилятор сам додумается что-то в функцию передать?

Vourhey, Humanitis, так это вижу не я один… ну повезло… а то думал — переработался)))

Большое спасибо, ошибка исчезла. Но появилась другая: в строке 21

Код

avonfunc.cpp: In function ‘int main(int, char**)’:
avonfunc.cpp:21: ошибка: expected primary-expression before ‘double’
avonfunc.cpp:21: ошибка: expected primary-expression before ‘double’
avonfunc.cpp:21: ошибка: expected primary-expression before ‘double’
avonfunc.cpp:21: ошибка: expected primary-expression before ‘double’
avonfunc.cpp:21: ошибка: expected primary-expression before ‘double’



0



Супер-модератор

8783 / 2536 / 144

Регистрация: 07.03.2007

Сообщений: 11,873

02.03.2009, 17:31

6

L@m@kЪ, покажи снова код



1



L@m@kЪ

3 / 3 / 0

Регистрация: 19.10.2008

Сообщений: 31

02.03.2009, 17:41

 [ТС]

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
 
using namespace std;
 
void func (double cena, double procent, double sum, double procentrub, double procsum);
 
void func (double cena, double procent, double sum, double procentrub, double procsum) //Функция подсчёта и вывода информации
{ for (int cntr = 1; cena != 0; cntr++)
    { cout << "nВведите цену " << cntr << "-го товара: ";
        cin >> cena;
        if (cena != 0)
        { cout << "Введите скидку " << cntr << "-го товара: ";
            cin >> procent;
            procentrub = (cena / 100) * procent; // Скидка в рублях
            procsum += procentrub;
            sum = sum + (cena - procentrub); } // Цена товара со скидкой
        else
        {    cout << "nИтоговая цена: " << sum << endl; } } }
 
int main (int argc, char *argv[])
{ func (double cena, double procent, double sum, double procentrub, double procsum); }



0



Humanitis

176 / 168 / 27

Регистрация: 12.01.2009

Сообщений: 430

02.03.2009, 17:42

8

оригинальноСначала надо объявить переменные ,а потом их передавать в функцию. А ты их объявляешь в теле вызова функции

C++
1
2
3
4
int main (int argc, char *argv[])
{ 
double cena=2.0, procent=13.0,sum=40.0, procentrub=13.0,procsum=40.0;
func (cena, procent,  sum,  procentrub, procsum); }



1



Супер-модератор

8783 / 2536 / 144

Регистрация: 07.03.2007

Сообщений: 11,873

02.03.2009, 17:44

9

вы бы хоть одну книгу прочитали что ли, для начала…
попробуйте так:

Код

{ 
[COLOR=black]double cena, double procent, double sum, double procentrub, double procsum;[/COLOR]
... // ввод данных
func (cena, procent, sum, procentrub, procsum); 
}



1



3 / 3 / 0

Регистрация: 19.10.2008

Сообщений: 31

02.03.2009, 17:48

 [ТС]

10

Цитата
Сообщение от WooDooMan
Посмотреть сообщение

вы бы хоть одну книгу прочитали что ли, для начала…
попробуйте так:

Код

{ 
[COLOR=black]double cena, double procent, double sum, double procentrub, double procsum;[/COLOR]
... // ввод данных
func (cena, procent, sum, procentrub, procsum); 
}

Нда, действительно что-то туплю сегодня. Всем спасибо, всё работает



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

02.03.2009, 17:48

10

Laravel PHP 8 error
Generally, when you get this error your controller is likely expecting more arguments than you are passing to it.

However, if you got the above error after updating to PHP 8 then it’s likely an issue with PHP 8s expected parameter arrangement.

👉 Parameter arrangement in PHP 8

In PHP 8, all required parameters need to be in the first position of the method/function signature followed by optional parameters.


01: function person($name, $age=null) {
02:     echo $name;
03: }
04: 
05: person('eddymens');

If you happen to place optional parameters before required ones, PHP 8 will throw a deprecation error, which in itself is not a show-stopper.


01: function person($age=null, $name) {
02:     echo $name;
03: }
04: 
05: person('eddymens', 25);

Deprecated: Required parameter $name follows optional parameter $age in /tmp/dxhracul7n453yt/tester.php on line 3 25

👉 Parameter placement error in Laravel

In Laravel however, you might end up with an ArgumentCountError: error instead of a deprecation message.
The deprecation error is only thrown when you call on the function directly, when you use a function like call_user_func() to call on your function you end up with the ArgumentCountError: error, and laravel relies a lot on such functions to call on different parts of your code.

And this is why you end up with an error that doesn’t clearly state the problem.

👉 Fixing the error

Laravel controllers typically have the $request argument passed in as a required parameter which is then resolved using a dependency container.
You are likely to hit the ArgumentCountError: if you do not have the $request argument as the first argument if you have optional parameters.


01:  public function index($slug = null, $tag = null, Request $request) {
02:     ...
03:  }
04: ...

To fix this place the $request variable as the first parameter of the method and this should fix it.


01:  public function index( Request $request, $slug = null, $tag = null) {
02:         ...
03:  }
04: 

Here is another article you might like 😊 «Laravel: Create Controllers In A Subfolder (Sub Controller)»

Получил ошибку:

Too few arguments to function AppHttpControllersUserController::LoginWithVk(), 0 passed in /localhost/app/Http/Controllers/UserController.php on line 25 and exactly 1 expected

web.php

Route::get('/login/{type}', [AppHttpControllersUserController::class, 'login']);

UserController.php

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateRoutingController;
use IlluminateSupportFacadesAuth;
use romanzippTwitchEnumsEventSubType;
use romanzippTwitchTwitch;
use romanzippTwitchEnumsGrantType;

class UserController extends Controller
{
    public function login($type){
        switch ($type) {
            case "twitch":
                $this->LoginWithTwitch();
                break;
            case "youtube":
                $this->LoginWithYouTube();
                break;
            case "vk":
                $this->LoginWithVk();
                break;

            default:
                return redirect()->route('landing');
                break;
        }
    }
    public function LoginWithVk(Request $request){
        if (empty($request->get('code'))) {
            return $this->VKRedirectToLogin();
        } else {
            $token = $this->VKGetAuthToken($request->get('code'));
            if (isset($token['access_token'])) {
                $userInfo = $this->VKGetUserInfo($token);
                if (isset($userInfo['response'][0]['id'])) {
                    $userInfo = $userInfo['response'][0];
                    $u = User::where('user_vk', $userInfo["id"])->first();
                    if(!($u)){
                        $data = ['user_email' => '', 'user_login' => 'vkid'.$userInfo["id"], 'user_login_show' => $userInfo['first_name'] . " " . $userInfo['last_name'], 'user_domain' => 'vkid'.$userInfo["id"], 'user_vk' => $userInfo["id"],
                            'user_group' => 1, 	'user_wallets' => '{"qiwi":"null","webmoney":"null","yamoney":"null","bank":"null","paypal":null}', 'user_wallets_pay' => 0,
                            'user_paypal' => '{"clientid":"","secret":"","email":"","on":"0"}', 'user_stream_status' => 0, 'user_avatar' => $userInfo["photo_big"], 'user_donate_page' => '{"min_sum":"1","rec_sum":"50","text":"","fuck_filter":"0","fuck_name_filter":"0","fuck_words":"","bg_color":"#e0e0e0","bg_type":"1","bg_size":"auto","bg_image":"","bg_image_name":"","bg_repeat":"no-repeat","bg_position":"center","bg_header_type":"1","bg_header_image":"","bg_header_size":"auto","bg_header_repeat":"no-repeat","bg_header_position":"center","bg_header_color":"#f2f2f2","text_header_color":"#000000","btn_color":"#ff5400","btn_text_color":"#ffffff","comission":"0"}',
                            'user_reg_time' => now(), 'user_reg_ip' => $_SERVER['REMOTE_ADDR']];
                        $user = User::create($data);
                        $remember = true;
                        Auth::login($user, $remember);
                        return redirect()->route('dashboard');
                    } else {
                        $user = User::where('user_vk', $userInfo["id"])->first();
                        $user->update(['user_last_login_time' => now(), 'user_last_ip' => $_SERVER['REMOTE_ADDR']]);
                        $remember = true;
                        Auth::login($user, $remember);
                        return redirect()->route('dashboard');
                    }
                }
            }
        }
    }

    /*VKAuth*/
    private function VKRedirectToLogin()
    {
        $url = 'http://oauth.vk.com/authorize';
        $params = array(
            'client_id' => config('services.vkontakte.client_id'),
            'redirect_uri' => config('services.vkontakte.redirect'),
            'response_type' => 'code'
        );
        return redirect($url . '?' . urldecode(http_build_query($params)));
    }

    private function VKGetAuthToken($code)
    {
        $params = [
            'client_id' => config('services.vkontakte.client_id'),
            'client_secret' => config('services.vkontakte.client_secret'),
            'code' => $code,
            'redirect_uri' => config('services.vkontakte.redirect'),
        ];
        return json_decode($this->get_curl('https://oauth.vk.com/access_token' . '?' . urldecode(http_build_query($params))), true);
    }

    private function VKGetUserInfo($token)
    {
        $params = [
            'uids' => $token['user_id'],
            'fields' => 'uid,first_name,last_name,photo_big,email',
            'access_token' => $token['access_token'],
            'v' => '5.103'
        ];
        return $userInfo = json_decode($this->get_curl('https://api.vk.com/method/users.get' . '?' . urldecode(http_build_query($params))), true);
    }

    function get_curl($url)
    {
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $output = curl_exec($ch);
            echo curl_error($ch);
            curl_close($ch);
            return $output;
        } else {
            return file_get_contents($url);
        }
    }
    /*EndVKAuth*/
}

Понравилась статья? Поделить с друзьями:
  • Ошибка tokyo ghoul re call to exist
  • Ошибка to run this application you must install net
  • Ошибка tns 12560 tns protocol adapter error
  • Ошибка tns 12541 tns no listener
  • Ошибка tls соединения что это