Error c2078 too many initializers

Why does this code not work? My IDE is Visual Studio 2013. #include float tempatureGuide(float F, float C); #define FREEZING_PT 32.0f #define SCALE_FACTOR (5.0f/9.0f) int main(void...

Why does this code not work? My IDE is Visual Studio 2013.

#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
    float fahrenheit = 0.0;
    float celsius = 0.0 ;
    int convertTemp;
    printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit:            ");
    scanf ("%d", &convertTemp);

    if (convertTemp == 0)
    {
        // compute Celsius
        printf("Enter Fahrenheit temperture: ");
        scanf("%f", &fahrenheit);
        celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
        printf("Fahrenheit = %f  and Celsius = %fn", fahrenheit, celsius);
        float tempatureGuide(fahrenheit, celsius);  // Error here
    }
    else
    {
        // compute fahrenheit
        printf("Enter the temperature in degrees fahrenheitnn");
        scanf("%f", &fahrenheit);
        celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
        printf("The converted temperature is %f", celsius);
        float tempatureGuide(fahrenheit, celsius);    // and here

    }
    return (0);
}

float tempatureGuide(float F, float C){
    if (F < 32 || C < 0)
        printf("It is freezing!");
    else if (F <= 60 || C <= 16)
        printf("It is cold");
    else if (F >= 70 || C >= 21)
        printf("It is just right");
    else if (F >= 82 || C >= 28)
        printf("It is warm");
    else if (F > 95 || C > 35)
        printf("It is hot");
    else
        printf("Please enter a number!");
    return (0);
}

The goal here is to add to the converting temperature project I did earlier and add an if else statement function to it that comments on the temp. The error I get is

Error   3   error C2078: too many initializes

on both the lines where I call my function. I searched for an answer but couldn’t find any.

Klas Lindbäck's user avatar

asked Feb 13, 2015 at 7:11

Hawkins Lance's user avatar

4

This line looks like an attempt at a C++ initialization of a float with one too many arguments (hence the «too many initializers» error), not like a function call.

float tempatureGuide(fahrenheit, celsius);

Presumably you want to call the function and store the result in a variable:

float temp = tempatureGuide(fahrenheit, celsius);

Or just call the function and ignore the return value:

tempatureGuide(fahrenheit, celsius);

Especially since your function always returns 0, so one might question the need for a non-void return type.

answered Feb 13, 2015 at 7:13

juanchopanza's user avatar

juanchopanzajuanchopanza

221k33 gold badges398 silver badges474 bronze badges

1

You need to call a function

float tempatureGuide(float fahrenheit, float celsius) { //...}

as

float retval = tempatureGuide(fahrenheit, celsius);

or least

tempatureGuide(fahrenheit, celsius);  // not need to use return value

Only.

Sourav Ghosh's user avatar

Sourav Ghosh

132k16 gold badges184 silver badges258 bronze badges

answered Feb 13, 2015 at 7:16

Vagish's user avatar

VagishVagish

2,50018 silver badges32 bronze badges

2

That is just a simple error. Please change 2 lines of code where you are calling tempatureGuide(fahrenheit, celsius); function as follows.

float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);

I tested the same in my VS2013 as you are using the same with the mentioned changes. I am able to compile and run it successfully. See the attachment.
enter image description here

answered Feb 13, 2015 at 7:23

Shivaraj Bhat's user avatar

Shivaraj BhatShivaraj Bhat

8332 gold badges9 silver badges20 bronze badges

3

Just call the function and return it to a variable of the same type.

answered Aug 24, 2021 at 15:50

chicken_milk's user avatar

1

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2078

Compiler Error C2078

11/04/2016

C2078

C2078

9bead850-4123-46cf-a634-5c77ba974b2b

Compiler Error C2078

too many initializers

The number of initializers exceeds the number of objects to be initialized.

The compiler can deduce the correct assignment of initializers to objects and inner objects when inner braces are elided from the initializer list. Complete bracing also eliminates ambiguity and results in correct assignment. Partial bracing can cause C2078 because of ambiguity in the assignment of initializers to objects.

The following sample generates C2078 and shows how to fix it:

// C2078.cpp
// Compile by using: cl /c /W4 C2078.cpp
struct S {
   struct {
      int x, y;
   } z[2];
};

int main() {
   int d[2] = {1, 2, 3};   // C2078
   int e[2] = {1, 2};      // OK

   char a[] = {"a", "b"};  // C2078
   char *b[] = {"a", "b"}; // OK
   char c[] = {'a', 'b'};  // OK

   S s1{1, 2, 3, 4};       // OK
   S s2{{1, 2}, {3, 4}};   // C2078
   S s3{{1, 2, 3, 4}};     // OK
   S s4{{{1, 2}, {3, 4}}}; // OK
}

I’m using VS2013.

I can initialize an «array of strings» like this without any problems:

char titles[4][80] = { "Dad", "Idiot", "Donut Lover", "Fewl" }; // OK!

I have a struct declared like this:

typedef struct
{
    char name[80];    
    char titles[4][80];
} Dude;

When I try to initialize the struct like this:

Dude homer =
{
    .name = "Homer",
    .titles = { "Dad", "Idiot", "Donut Lover", "Fewl" } // error?
};

I get an «error C2078: too many initializers». This is because of the array initialization- If I remove the

.titles = { "Dad", "Idiot", "Donut Lover", "Fewl" }

line, but leave the

.name = "Homer"

line, the error goes away. This means to me that designated initializers are at least partially implemented in VS.

Why am I getting this error?

If I change the declaration of the struct to look like this

typedef struct
{
    char name[80];
    char *titles[4];
} Dude;

the error goes away. This is, however, not a change I can make. Other parts of the code base require that the size of this struct is exactly 400 bytes.

Further, I’m quite aware that I could use strcpy to fill in each field, but that does not answer my question. I also realize I could initialize the struct without using designated initializers, but again that is not my question.

Почему этот код не работает? Моя IDE — это Visual Studio 2013.

#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit:            ");
scanf ("%d", &convertTemp);

if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f  and Celsius = %fn", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius);  // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheitnn");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius);    // and here

}
return (0);
}

float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}

Цель состоит в том, чтобы добавить к проекту преобразования температуры, который я делал ранее, и добавить if else Функция заявления к нему, что комментирует темп. Я получаю ошибку

Error   3   error C2078: too many initializes

на обеих линиях, где я вызываю свою функцию. Я искал ответ, но не мог найти.

0

Решение

Эта строка выглядит как попытка инициализации C ++ float с одним слишком много аргументов (следовательно, «слишком много инициализаторов«ошибка), а не как вызов функции.

float tempatureGuide(fahrenheit, celsius);

Предположительно, вы хотите вызвать функцию и сохранить результат в переменной:

float temp = tempatureGuide(fahrenheit, celsius);

Или просто вызовите функцию и проигнорируйте возвращаемое значение:

tempatureGuide(fahrenheit, celsius);

Тем более что ваша функция всегда возвращает 0Таким образом, можно задаться вопросом о необходимости не пустого типа возврата.

3

Другие решения

Вам нужно вызвать функцию

float tempatureGuide(float fahrenheit, float celsius) { //...}

как

float retval = tempatureGuide(fahrenheit, celsius);

или хотя бы

tempatureGuide(fahrenheit, celsius);  // not need to use return value

Только.

1

Это просто простая ошибка. Пожалуйста, измените 2 строки кода, где вы вызываете tempatureGuide (по Фаренгейту, Цельсию); функционировать следующим образом.

float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);

Я протестировал то же самое в моем VS2013, так как вы используете то же самое с упомянутыми изменениями. Я могу скомпилировать и запустить его успешно. Смотрите вложение.
введите описание изображения здесь

0

  • Forum
  • General C++ Programming
  • error C2078: too many initializers

error C2078: too many initializers

I want to change this to use user defined functions working on the first and i get this error, not sure how to fix it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 #include <iostream>

using namespace std;

const int SENTINEL = -99;

	// Declaring variables
	char letter;    //letter chosen from the menu
	int i;		    //quantity of numbers user will enter	
	int counter;	//loop control variables
	int number;     // variable to store new number
	int largest;     // variable to store largest number
	int smallest; 
	int number1;
	int largest2;
	int biggestNumber (number1, largest2);

int main ()
{

	// Initializing variables
	largest = -99999999999;
	smallest = 99999999999;
	// Big loop here for the condition of the Application running
	do
	{
		//displaying Menu
		cout << "Please Select One of the Following Choices" << endl;
		cout << "A: Find the largest number with a known quantity of number " << endl;
		cout << "B: Find the smallest number with an unknown quantity of number " << endl;
		cout << "C: Quit" << endl;	
		cout << "Please enter your choice: ";
		cin >> letter;
		cout << endl;
		
		switch (letter)
		{
		case 'A':
		case 'a':
				cout << "How many numbers would you like to enter"<< " ";
				cin >> i;
				cout << endl; 
				cout << "Please enter your numbers" << endl;
				for (counter = 1; counter <= i; counter++)
				{
					cin >> number;
				
				if	biggestNumber (number, largest)
					largest = number;
				}
				cout << "The largest number you entered is" << " " << largest;
				cout << " ";
				cout << endl;
				break;

		case 'B':
		case 'b':
			cout << "Please enter your numbers with your last number being" << " " << SENTINEL << endl;
			cin >> number;
			while (number != SENTINEL)
			{
					if (number < smallest)
						smallest = number;
					cin >> number;
			}
			cout << "The smallest number you entered is" << " " << smallest << endl;
		}
	}
	while (letter != 'C' && letter != 'c');

	cout << endl;

     int biggestNumber
	(
	(number1 > largest2)
	)

	;return 0;
} 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 #include <iostream>

using namespace std;

const int SENTINEL = -99;

	int biggestNumber (int, int);

int main ()
{
	// Declaring variables
	;char letter;    //letter chosen from the menu
	int i;		    //quantity of numbers user will enter	
	int counter;	//loop control variables
	int number;     // variable to store new number
	int largest;     // variable to store largest number
	int smallest; 
	int number1;
	int largest2;





	// Initializing variables
	largest = -99999999999;
	smallest = 99999999999;
	// Big loop here for the condition of the Application running
	do
	{
		//displaying Menu
		cout << "Please Select One of the Following Choices" << endl;
		cout << "A: Find the largest number with a known quantity of number " << endl;
		cout << "B: Find the smallest number with an unknown quantity of number " << endl;
		cout << "C: Quit" << endl;	
		cout << "Please enter your choice: ";
		cin >> letter;
		cout << endl;
		
		switch (letter)
		{
		case 'A':
		case 'a':
				cout << "How many numbers would you like to enter"<< " ";
				cin >> i;
				cout << endl; 
				cout << "Please enter your numbers" << endl;
				for (counter = 1; counter <= i; counter++)
				{
					cin >> number;
				
				if	biggestNumber (number, largest)
					largest = number;
				}
				cout << "The largest number you entered is" << " " << largest;
				cout << " ";
				cout << endl;
				break;

		case 'B':
		case 'b':
			cout << "Please enter your numbers with your last number being" << " " << SENTINEL << endl;
			cin >> number;
			while (number != SENTINEL)
			{
					if (number < smallest)
						smallest = number;
					cin >> number;
			}
			cout << "The smallest number you entered is" << " " << smallest << endl;
		}
	}
	while (letter != 'C' && letter != 'c');

	cout << endl;

     int biggestNumber
	(
	(number1 > largest2)
	)

	;return 0;
} 

error C2061: syntax error : identifier ‘biggestNumber’

is the only error i got now if anyone can help fix that

Line 48: No () around the if condition.
Lines 73-76: Function definition inside another function. The definition itself would be wrong even if this wasn’t so. Badly formed parameter list. Missing function body.

Reread your source material on functions.

Last edited on

i fixed it now

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
 

  #include <iostream>

using namespace std;

const int SENTINEL = -99;

    // Declaring variables
    char letter;    //letter chosen from the menu
    int i;            //quantity of numbers user will enter
    int counter;    //loop control variables
    int number;     // variable to store new number
    int largest;     // variable to store largest number
    int smallest;
    int number1;
    int largest2;
	int number2;
	int smallest2;
	int smallestNumber (int number2, int smallest2);
    int biggestNumber (int number1, int largest2);  // << declare parameters as ints

int main ()
{

    // Initializing variables
    largest = -999999999;      // << changed these so they will fit an int
    smallest = 999999999;
    // Big loop here for the condition of the Application running
    do
    {
        //displaying Menu
        cout << "Please Select One of the Following Choices" << endl;
        cout << "A: Find the largest number with a known quantity of number " << endl;
        cout << "B: Find the smallest number with an unknown quantity of number " << endl;
        cout << "C: Quit" << endl;
        cout << "Please enter your choice: ";
        cin >> letter;
        cout << endl;

        switch (letter)
        {
        case 'A':
        case 'a':
                cout << "How many numbers would you like to enter"<< " ";
                cin >> i;
                cout << endl;
                cout << "Please enter your numbers" << endl;
                for (counter = 1; counter <= i; counter++)
                {
                    cin >> number;

                if  (  biggestNumber (number, largest))  // () added
                    largest = number;
                }
                cout << "The largest number you entered is" << " " << largest;
                cout << " ";
                cout << endl;
                break;

        case 'B':
        case 'b':
            cout << "Please enter your numbers with your last number being" << " " << SENTINEL << endl;
            cin >> number;
            while (number != SENTINEL)
            {
                    if (  smallestNumber (number, largest))
                        smallest = number;
                    cin >> number;
            }
            cout << "The smallest number you entered is" << " " << smallest << endl;
        }
    }
    while (letter != 'C' && letter != 'c');

    cout << endl;

//     int biggestNumber    << moved
  //  (
  //  (number1 > largest2)
  //  )

;return 0;
}

   // your function goes here not inside main()
    int biggestNumber (int number1, int largest2)
    {
    // is this what you want it to do?
    if(number1 > largest2) return number1; else return largest2;
    }

	int smallestNumber (int number2, int smallest2)
	{
	if(number2 < smallest2) return smallest2; else return smallest2;
	}

*Never* but the else statement in the same line as the if statement. It makes code much harder to read.
In fact, it’s not recommendable to put the block in the same line as the statement.

There’s an extra semicolon on line 83.

Last edited on

Topic archived. No new replies allowed.

Фантомас

1 / 1 / 0

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

Сообщений: 18

1

13.02.2013, 13:37. Показов 7316. Ответов 4

Метки нет (Все метки)


Создаю текстовый массив. Выдает ошибку «error C2078: слишком много инициализаторов». При создании Int массива все нормально, а при создании екстового валит ошибку ( error C2078: слишком много инициализаторов ):

C++
1
char students[3] = {"a", "b", "c"};

Что я наделал?)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Issues

433 / 368 / 149

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

Сообщений: 961

13.02.2013, 13:40

2

C++
1
char students[3] = {'a', 'b', 'c'};



1



1 / 1 / 0

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

Сообщений: 18

13.02.2013, 13:45

 [ТС]

3

КАК, БЛИН? О_о



0



3985 / 3255 / 909

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

Сообщений: 12,102

Записей в блоге: 1

13.02.2013, 13:49

4

что не ясно?
‘a’ — это char
«a»- это char*
«aaaa» это char*



1



1 / 1 / 0

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

Сообщений: 18

13.02.2013, 16:37

 [ТС]

5

Та ясно, просто после детального изучения рнр строгий синтаксис смотрится устарашающе….



1



That’s because there are too many initializers :P

You are specifying the array as 5×4, yet you have initializers 20×2

Either use static DWORD 2DArray[20][2] = or change the initializer like so:

static DWORD 2DArray[5][4] =
{
    { 0 , 1 , 2 , 3 }  
    { 1 , 1 , 2 , 3 } 
    { 2 , 1 , 2 , 3 }  
    { 3 , 1 , 2 , 3 } 
    { 4 , 1 , 2 , 3 } 
}

EDIT: Perhaps you meant:

static DWORD 3DArray[4][5][2] =
{    {       { 0 , 1 },         { 1 , 4 },  
       { 2 , 5 },   
       { 3 , 6 },   
       { 4 , 25 }
    },
    {
       { 0 , 2 },  { 1 , 9 }, { 2 , 10}, { 3 , 11}, { 4 , 26 }
    },
    {
       { 0 , 3 },  { 1 , 13}, { 2 , 14}, { 3 , 15}, { 4 , 23 }
    },
    {
       { 0 , 4 },  { 1 , 17}, { 2 , 18}, { 3 , 19}, { 4 , 22 }
    }
}

You don’t need the first digit if these are the real numbers as they relate to the index anyway.

I would suggest:

static DWORD 3DArray[4][5] =
{    {        1, 4, 5, 6, 25 },
    { 2 , 9 , 10 , 11 , 26 },
    { 3 , 13 , 14 , 15 , 23 },
    { 4 , 17 , 18 , 19 , 22 }
}

Понравилась статья? Поделить с друзьями:
  • Error c2065 undeclared identifier error c2065 undeclared identifier
  • Error c2065 string необъявленный идентификатор
  • Error c2065 null необъявленный идентификатор
  • Error c2065 func undeclared identifier
  • Error c2065 cout необъявленный идентификатор