Error c2447 missing function header old style formal list

I got this error and I have no idea what's causing it. I haven't been able to find a clear solution online.
  • Remove From My Forums
  • Question

  • I got this error and I have no idea what’s causing it. I haven’t been able to find a clear solution online.

    Code:

    #include <iostream>
    using namespace std;

     int main()
    {

    int NUM1, NUM2;

    cout << «Enter your first number: «;
    cin >> NUM1;
    cout << endl;

    cout << «Enter your second number: «;
    cin >> NUM2;
    cout << endl; cout << endl;           //moves cursor two lines down

    int SUM = NUM1 + NUM2;                //Sum
    int DIFF = NUM1 — NUM2;               //Difference
    int PROD = NUM1 * NUM2;               //Product
    int INT_QUO = NUM1 / NUM2;            //Integer quotient
    float FLT_QUO = ((float)NUM1) / NUM2; //Float quotient

        cout << «Sum: » << SUM;                  cout << endl;
    cout << «Difference: » << DIFF;          cout << endl;
    cout << «Product: » << PROD;             cout << endl;
    cout << «Integer Quotient: » << INT_QUO; cout << endl;
    cout << «Float Quotient: » << FLT_QUO;   cout << endl;

    return 0;
    }

    Help would be appreciated!

Answers

  • I also tried a generic «Hello World» code to the program out and I got the exact same error messages.

    Code:

    #include <iostream>
    using namespace std;
    int main()
    {
    cout << «Hello world!n»;
    system(«pause»);
    return 0;
    }

    Here’s the full error message:

    1>—— Build started: Project: CS215Lab1_01092019, Configuration: Debug Win32 ——
    1>HelloWorld.cpp
    1>Lab1.cpp
    1>c:usersCgrunchsourcereposcs215lab1_01092019cs215lab1_01092019lab1.cpp(8): error C2447: ‘{‘: missing function header (old-style formal list?)
    1>c:usersCgrunchsourcereposcs215lab1_01092019cs215lab1_01092019lab1.cpp(10): fatal error C1004: unexpected end-of-file found

    The build output suggests that you have both HelloWorld.cpp and Lab1.cpp
    in the same project. The compile errors are from Lab1.cpp so remove that 
    program from the project and and do a Rebuild with just HelloWorld.cpp in
    the project.

    It would help if you described the steps you followed when creating this
    project. Did you start from an Empty Project? Or did you use one of the
    supplied templates such as Win32 Console Application?

    — Wayne

    • Marked as answer by

      Thursday, January 10, 2019 5:32 PM

  • I restarted VS2017 and reopened the Project. VS asked me if I wanted to «normalize line endings» and I clicked «Yes». I removed HelloWorld.cpp and the program works fine now.

    Thank you so much for your help! :)

    • Marked as answer by
      CGrunch
      Thursday, January 10, 2019 5:32 PM

I get this error but I have no idea where I could have went wrong here are the three functions below… I just really don’t understand what is missing

void InitBullet(Bullet bullet[], int size) //init bullet
{
    for (int i = 0; i < size; i++)
    {
        bullet[i].ID = BULLET; //ID
        bullet[i].speed = 10; //bullet speed (10)
        bullet[i].live = false; //bullet isnt live it hasnt been fired
    }
}

void drawBullet(Bullet bullet[], int size) //drawing bullet to screen
{
    for (int i = 0; i < size; i++)
    {
        if (bullet[i].live) //if bullet is live
            al_draw_filled_circle(bullet[i].x, bullet[i].y, 2, al_map_rgb(255, 0, 0)); //red circle primitives for bullets
    }
}

void fireBullet(Bullet bullet[], int size, submarine &sub) //
{
    for (int i = 0; i < size; i++) //looking for deadbullets 
    {
        if (!bullet[i].live)
        {
            bullet[i].x = sub.x + 17; // 17 looks the best
            bullet[i].y = sub.y;
            bullet[i].live = true; // turning the bullet on
            break; //only one at a time
        }

    }
{

talgatich-09

0 / 0 / 0

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

Сообщений: 15

1

16.05.2012, 17:42. Показов 6783. Ответов 11

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


C++
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
#include <conio.h>
#include <iostream.h>
#include <stdio.h>
#include <math.h>
int main ();
{ short int n,m,i,d,s=0;
cout <<"Vvedite chislo strol(m):";
cin>>m;
cout<<"Vvedite chislo stolbcov (n):";
cin>>n;
cout<<endl;
char**masnew=new chat*[n];
for (j=0;j<m;j++)masnew[j]=new char[n];
for(i=0;i<m;i++){
    masnew[i][j]=50+rad()%50
        printf(%sd;masnew[i][j];}
cout<<end;}
if(m<1) cout<< endl<<"1 strok ret";
else{
    cout<<endl<<"znachenie 1 strok:"<<endl;
    for(j=0;j<n;j++)
    {printf("%5d";masnew[0][j];
    s+=masnew[0][j];}
    cout <<endl<<"summe strok:"<<s<<endl;}
for(j=0;j<m,j++)delete[] masnew;
delete[]masnew;
cout<<endl;
return 0;
}

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



0



Infinity3000

1066 / 583 / 87

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

Сообщений: 1,255

16.05.2012, 17:44

2

C++
1
int main ();

убери двоеточие



0



0 / 0 / 0

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

Сообщений: 15

16.05.2012, 17:49

 [ТС]

3

В какой строке?



0



Infinity3000

1066 / 583 / 87

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

Сообщений: 1,255

16.05.2012, 17:57

4

Цитата
Сообщение от talgatich-09
Посмотреть сообщение

В какой строке?

извеняюсь, точку с запятой!

C++
1
int main ();

без точки запятой

C++
1
int main ()



0



0 / 0 / 0

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

Сообщений: 15

16.05.2012, 18:01

 [ТС]

5

Дальше прошел показывает 15 ошибок



0



Infinity3000

1066 / 583 / 87

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

Сообщений: 1,255

16.05.2012, 18:08

6

ну где ошибки? показывайте!

перед main()

добавте

C++
1
using namespace std;



0



talgatich-09

0 / 0 / 0

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

Сообщений: 15

16.05.2012, 18:12

 [ТС]

7

А нет правильно не надо точки с запятой,сейчас в 15 строке выдает ошибку error C2065: ‘rand’ : undeclared identifier

C++
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
#include <conio.h>
#include <iostream.h>
#include <stdio.h>
#include <math.h>
int main ()
{ short int n,m,j,i,d,s=0;
cout <<"Vvedite chislo strol(m):";
cin>>m;
cout<<"Vvedite chislo stolbcov (n):";
cin>>n;
cout<<endl;
char**masnew = new char *[n];
for(j=0;j<m;j++)masnew[j]=new char[n];
for(i=0;i<m;i++){
masnew[i][j]=50+rand()%50;
printf(%sd;masnew[i][j]);
cout<<end;}
if(m<1) cout <<endl<<"1 strok ret";
else{
cout <<endl<<"znachenie 1 stroki:"<<endl;
for(j=0;j<n;j++)
{printf("%5d";masnew[0][j];
s+=masnew[0][j];}
cout <<endl<<"summe strok:"<<s<<endl;}
for (j=0;j<m,j++) delete[] masnew;
delete[]masnew;
cout<<endl;
return 0;
}



0



1066 / 583 / 87

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

Сообщений: 1,255

16.05.2012, 18:21

8

Где вы вообще этот код взяли? тут в каждой строке ошибка!

Вы хоть пытались сами разобраться в чем проблема?

Хоть бы описали что должна делать данная программа!



0



0 / 0 / 0

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

Сообщений: 15

16.05.2012, 18:33

 [ТС]

9

1. С помощью динамического выделения памяти создать двухмерный массив размерностью m x n элементов указанного типа данных. Размерность массива вводить с клавиатуры.
2. Для выделения и освобождения памяти воспользоваться операторами new и delete.
3. Заполнить массив случайными значениями в заданном диапазоне.
4. Вывести на экран значения элементов массива в виде таблицы.
5. Вычислить сумму значений элементов указанного объекта с номером номер. Вывести на экран значения элементов и полученную сумму.
6. При выполнении операций заполнения массива значениями и вывода значений на экран необходимо использовать оператор цикла, указанный в задании.

Добавлено через 4 минуты
Братух помоги пожайлуста



0



Infinity3000

1066 / 583 / 87

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

Сообщений: 1,255

16.05.2012, 18:35

10

Исправил вашу программу! дальше сами!

C++
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
#include <iostream>
 
using namespace std;
 
int main()
{ 
    short int n, m, d, s = 0;
    cout << "Vvedite chislo strol(m):";
    cin >> m;
    cout << "Vvedite chislo stolbcov (n):";
    cin >> n;
    cout << endl;
 
    int **masnew = new int *[m];
    for(int j = 0; j < m; j++)
    {
        masnew[j] = new int[n];
    }
 
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            masnew[i][j]= 50 + rand() % 50;
            cout << masnew[i][j] << " ";
        }
        cout << endl;
    }
    if(m < 1)
    {
        cout << endl << "1 strok ret";
    }
    else
    {
        cout << endl << "znachenie 1 stroki:" << endl;
        for(int  j = 0; j < n; j++)
        {
            cout << masnew[0][j] << " ";
            s += masnew[0][j];
        }
        cout << endl << "summe strok:" << s << endl;
    }
 
    for (int j = 0; j < m; j++) 
        delete[] masnew[j];
    delete[] masnew;
    cout<<endl;
    system("pause >> null");
    return 0;
}



1



0 / 0 / 0

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

Сообщений: 15

16.05.2012, 18:36

 [ТС]

11

Добавилбиблиотеку #include <cstlib> показывает 1 ошибку,которая указывает на библотеку как неизвестная



0



0 / 0 / 0

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

Сообщений: 3

17.03.2013, 21:14

12

а как сделать тоже самое только с оператором do while ?



0



OK here’s the problem I am trying to write a program that is trying to find the average of a set of numbers and i keep getting the following error:

error C2447: ‘{‘ : missing function header (old-style formal list?)

what should i do to solve that problem in the following code:

#include <iostream>
#include <fstream> // I/O
#include <iomanip> // For setw()
using namespace std;

ofstream outputfile(«output.txt»);
const int MAX_FILE_NAME = 35; // Maximum space allocated for file name

void open_input(ifstream& input, char name[]); // Get file name & Open file
void find_max_min(ifstream& input, int& max, int& min); // Find max & min values
double find_average(ifstream& input); // Finds average
void output(const char name[], int max, int min, ostream& os = cout); // Print results

int main()
// Parameters: None
// Returns: Zero
// Calls: open_input(), find_max_min(), output()
{ char again; // Does user want to go through loop again?
char file_name[MAX_FILE_NAME + 1]; // Name of file to be processed
ifstream input_numbers; // For working with input file

int max, min; // Maximum and minimum numbers from file

double average;

cout << «This program can find the largest and smallest numbers in a filen»
<< «of integers.n» << endl;
system(«pause»); // Hold message on screen until key is pressed

do
{
system(«cls»); // Clear screen
open_input(input_numbers, file_name); // Get file name & open file
// find_max_min(input_numbers, max, min); // Find max & min values in file
average = find_average(input_numbers);

input_numbers.close(); // Close file
output(file_name, max, min); // Print results on screen
output(file_name, max, min, outputfile); // Print results on outputfile

cout << «nDo you want to process another file (Y/N)? «;
cin >> again;
cin.ignore(256, ‘n’); // Remove Enter key from keyboard buffer

} while ( again == ‘y’ || again == ‘Y’);

cout << «nEnd of Program!» << endl;
outputfile << «nnThanks for using MaxMin!f»;
outputfile.close();

return 0;
} // End of main()

void open_input(ifstream& input, char name[]) //Open file, exit on error
// Parameters: Variables for input file reference and input file name
// Returns: None
// Calls: None
{ int count = 0; // Count number of tries

do // Continue until we get a valid file name and can open file
{
count++;

if (count != 1) // Issue error message if we are trying again.
{ cout << «naInvalid file name or file does not exist. Please try again.»
<< endl;
}

cout << «nEnter the input file name (maximum of » << MAX_FILE_NAME
<< » characters please)n:> «;
cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
cin.ignore(256, ‘n’); // Remove Enter key from keyboard buffer

input.clear(); // Clear all error flags, if any, from prev try
input.open(name, ios_base::in); // Open only if file exists

} while (input.fail() ); // If can’t open file, try again
} // End of open_input()

void find_max_min(ifstream& input, int& max, int& min) // Find max & min values
// Parameters: Variables for file reference and max and min values
// Returns: None
// Calls: None
{
int value; // Value from file

input >> value; // Read first number
max = min = value; // Initialize max & min to first number
while (input >> value) // Continue as long as we can read a number from file.
{
if (value > max) max = value;
if (value < min) min = value;
}
} // End of find_max_min()

double find_average(ifstream& input);
// Parameters: Variables for file reference and max and min values
// Returns: None
// Calls: None
{
double value; // Value from file
double sum = 0;
int count= 0;

// Initialize max & min to first number
while (input >> value) // Continue as long as we can read a number from file.
{
sum += value;
count++;
}

return sum/count;
}

void output(const char name[], int max, int min, ostream& os) // Print results
// Parameters: File name, max & min values from file, output stream
// Returns: None
// Calls: None
{ os << «nnInput File Name : » << name << endl;
os << «Largest Number in File : » << setw(8) << max << endl;
os << «Smallest Number in File: » << setw(8) << min << endl;
} // End of output()

regard all solutions to the problem to alabamafan198424@aol.com

Last edited on

1
2
3
4
5
double find_average(ifstream& input); //<- accidental semicolon here
// Parameters: Variables for file reference and max and min values
// Returns: None
// Calls: None
{

I can’t believe I actually found that.

thanks for helping me pinpoint out what was wrong with it and if you can fix it without any warnings let me know what i need to fix

ok after i fixed the error and compiled the program i got 2 warnings so i ignored the warnings and ran the program and when i ran the program i got a run-time error saying the following:

Run-Time Check Failure #3 — The variable ‘min’ is being used without being defined.
Run-Time Check Failure #3 — The variable ‘max’ is being used without being defined.

Can anyone tell me how this can be fixed.

I can’t find anything wrong.

I think the actual errors say:

Run-Time Check Failure #3 — The variable ‘min’ is being used without being initialised.
Run-Time Check Failure #3 — The variable ‘max’ is being used without being initialised.

it helps if you use code tags:

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
int main()
// Parameters: None
// Returns: Zero
// Calls: open_input(), find_max_min(), output()
{ char again; // Does user want to go through loop again?
char file_name[MAX_FILE_NAME + 1]; // Name of file to be processed
ifstream input_numbers; // For working with input file

int max, min; // Maximum and minimum numbers from file

double average;

cout << "This program can find the largest and smallest numbers in a filen"
<< "of integers.n" << endl;
system("pause"); // Hold message on screen until key is pressed

do
{
system("cls"); // Clear screen
open_input(input_numbers, file_name); // Get file name & open file
// find_max_min(input_numbers, max, min); // Find max & min values in file
average = find_average(input_numbers);

input_numbers.close(); // Close file
output(file_name, max, min); // Print results on screen 

You’ll notice you declare variables min and max on line 9, but you never set them to anything. When you attempt to print them on line 25, since they’re not assigned any initial value, you will print garbage (this would have more serious consequences if you were doing something other than printing — which is why the compiler issues this kind of warning)

Oh, son of a bitch!
I totally missed the fact that line 21 is commented.
I finally have a good excuse to ban the space after the comment token.

well i have looked the problem over and over and cant still seem to find what needs to be initialized in the program cause i have tried setting the max and min both to zero and when i run the program i am getting a return value of zero as my answer so i dont know if i am doing the math wrong or what but i would like to know what i should do to initialize the max and min in this program

Here is the basic steps of your program:

1. Open File open_input(input_numbers, file_name); // Get file name & open file

2. Find average average = find_average(input_numbers);

3. Close Input file input_numbers.close(); // Close file

4. send MIN and MAX output to screen output(file_name, max, min); // Print results on screen

5. Send MIN and Max output to fileoutput(file_name, max, min, outputfile); // Print results on outputfile

There is a step missing isn’t there between steps 3 and 4

Topic archived. No new replies allowed.


Recommended Answers

http://www.freewebs.com/yb2pls/index.htm

#include<iostream.h>

struct temperature_node
{
	int day;
	float temperature;
	temperature_node *next;
};

temperature_node *head_ptr;
temperature_node *current_ptr;

int get_temp(int days, float &temp);
void show_temps();
void remove_temps();
void add_temp(int days, float temp);
void move_c_to_end();

int main()
{
	int days;
	float temp;

	if(get_temp(days, temp))
	{
		head_ptr = new …

Jump to Post

I am writing a program using a linked list and I am almost to the point where I can compile and run it but I keep on getting this error message: error C2447: missing function header (old-style formal list?). What does it mean? I looked through the code but I …

Jump to Post

I have a code snippet about singly / doubly linked lists if you run into any more trouble. Watch out for <iostream.h>, it should be ‘updated’ to

#include <iostream>
using namespace std;

as ive heard not all compilers / OS whatever support <iostream.h> anymore as it is …

Jump to Post

All 10 Replies

Member Avatar

18 Years Ago

http://www.freewebs.com/yb2pls/index.htm

#include<iostream.h>

struct temperature_node
{
	int day;
	float temperature;
	temperature_node *next;
};

temperature_node *head_ptr;
temperature_node *current_ptr;

int get_temp(int days, float &temp);
void show_temps();
void remove_temps();
void add_temp(int days, float temp);
void move_c_to_end();

int main()
{
	int days;
	float temp;

	if(get_temp(days, temp))
	{
		head_ptr = new temperature_node;
		head_ptr->day = days;
		head_ptr->temperature = temp;
		head_ptr->next = NULL;
		while(get_temp(days, temp))
		{
			add_temp(days, temp);
		}
		show_temps();
		remove_temps();
	}
	return 0;
}

int get_temp(int days, float &temp)
{
	int keep_data = 1;

	cout << "enter the days for which you have data ";
	cin >> days;
	if(days != 0)
	{
		cout << "enter the temperature ";
		cin >> temp;
	}
	else
	{
		keep_data = 0;
	}
	return(keep_data);
}

void add_temp(int days, float temp)
{
	temperature_node *new_rec_ptr;
	new_rec_ptr = new temperature_node;

	new_rec_ptr->day = days;
	new_rec_ptr->temperature = temp;
	new_rec_ptr->next = NULL;

	move_c_to_end();
	current_ptr->next = new_rec_ptr;
}

void move_c_to_end()
{
	current_ptr = head_ptr;
	
	while(current_ptr->next != NULL)
	{
		current_ptr = current_ptr->next;
	}
}

void show_temps()
{
	current_ptr = head_ptr;

	do
	{
		cout << current_ptr->day << endl;
		cout << current_ptr->temperature << endl;
	} while(current_ptr != NULL);
}

void remove_temps()
{
	temperature_node *temporary_ptr;

	current_ptr = head_ptr;

	do
	{
		temporary_ptr = current_ptr->next;
		delete current_ptr;
		current_ptr = temporary_ptr;
	}while(temporary_ptr != NULL);
}

view my site http://www.freewebs.com/yb2pls/index.htm
and sign the guest book

Member Avatar

18 Years Ago

I am writing a program using a linked list and I am almost to the point where I can compile and run it but I keep on getting this error message: error C2447: missing function header (old-style formal list?). What does it mean? I looked through the code but I cannot find anything wrong with it.

Notice the misplaced semicolon.

int main()[B];[/B]
{

Member Avatar


1o0oBhP

4



Posting Pro in Training


18 Years Ago

I have a code snippet about singly / doubly linked lists if you run into any more trouble. Watch out for <iostream.h>, it should be ‘updated’ to

#include <iostream>
using namespace std;

as ive heard not all compilers / OS whatever support <iostream.h> anymore as it is non standardised! :)

Member Avatar

18 Years Ago

Ok, I have made a few modifications and the program actually runs; but only to a certain point. Just so you have an idea, this program is supposed to consist of asking the user for the number of days that heshe has temperatures for and putting them in a linked list. when I display them at the end of the program the average temperature is suposed to be calculated also. I do not have anything that calculates the average as of yet but I’m not to worried. The problem I seem to be having now is that nodes are not being added. I think it is because of something in the get_temp function. any help is greatly appreciated. Here is the code:

#include <iostream>
using namespace std;

struct temperature_node
{
	int day;
	float temperature;
	temperature_node *next;
};

temperature_node *head_ptr;
temperature_node *current_ptr;

int day_counter = 0;

int get_temp(int days, float &temp);
void show_temps();
void remove_temps();
void add_temp(int days, float temp);
void move_c_to_end();

int main()
{
	int days = 0;
	float temp;

	if(get_temp(days, temp))
	{
		head_ptr = new temperature_node;
		head_ptr->day = days;
		head_ptr->temperature = temp;
		head_ptr->next = NULL;
	while(get_temp(days, temp))
		{
			add_temp(days, temp);
		}
	show_temps();
	remove_temps();
	}
return 0;
}

int get_temp(int days, float &temp)
{
	int keep_data = 1;

	if(days <= 0)
	{
		cout << "enter the number of days for which you have temperatures ";
        cin >> days;
	}

	while(day_counter != days)
	{
		cout << "Enter temperature for day " << day_counter + 1 << endl;
		cin >> temp;
		day_counter++;
	}

	if(day_counter == days)
	{
		keep_data = 0;
	}

	return(keep_data);
}

void add_temp(int days, float temp)
{
	temperature_node *new_rec_ptr;
	new_rec_ptr = new temperature_node;

	new_rec_ptr->day = days;
	new_rec_ptr->temperature = temp;
	new_rec_ptr->next = NULL;

	move_c_to_end();
	current_ptr->next = new_rec_ptr;
}

void move_c_to_end()
{
	current_ptr = head_ptr;

	while(current_ptr->next != NULL)
	{
		current_ptr = current_ptr->next;
	}
}

void show_temps()
{
	current_ptr = head_ptr;

	do
	{
		cout << current_ptr->day << endl;
		cout << current_ptr->temperature << endl;
	} while(current_ptr != NULL);
}

void remove_temps()
{
	temperature_node *temporary_ptr;

	current_ptr = head_ptr;

	do
	{
		temporary_ptr = current_ptr->next;
		delete current_ptr;
		current_ptr = temporary_ptr;
	}while(temporary_ptr != NULL);
}

Member Avatar


1o0oBhP

4



Posting Pro in Training


18 Years Ago

this program is supposed to consist of asking the user for the number of days that heshe has temperatures for and putting them in a linked list.

Is this for an assignment?? otherwise if you are ASKING for the number of days why not declare an array with the given size:

data_type *data; // data_type is your data type (char/int/long ect....)

data = (data_type*)new data_type[size]; // size is the number of elements
delete [] data; // when you have finished with it delete it!

Member Avatar

18 Years Ago

Yes, actually this is an assignment, :o but I don’t want anybody to do it for me, I just need some hints. As you can probably tell I am very new at this, and I would not be posting here because I know that it is somewhat annoying to have everybody wanting someone else to do their homework for them. However I have a matter of days to get this done and I spend all my time on the computer working on it. The requirements for the program are: to write a program using a linked list that prompts the user for the days and temperatures and then calculates the average temperature. I have modified the get_temp function from the last post, and now the output displays the last day and the first temperature.

Here is the modified section of code:

int get_temp(int days, float &temp)
{
	int keep_data = 1;

    if(day_counter == days)
	{
		keep_data = 0;
	}
	else
	{
		days = day_counter + 1; // note that day_counter is a global variable
		cout << days;
		cout << "enter the temperature for day " << day_counter + 1 << endl;
		cin >> temp;
		day_counter++;
	}
	return(keep_data);
}

Member Avatar

18 Years Ago

I do not know if anyone is even paying attention to this thread anymore but I found something wrong with the program nevertheless. In my show_temps function I forgot to add current_ptr = current_ptr->next; . That explains ALOT. Anyway, the program now displays all the temperatures the user adds but it only displays the last day. For example: Day: Temperature:
3 10
3 20
3 32.2
any ideas on how to fix this would be appreciated. If there is anyone out there reading this and they do not mind helping me, here is newest version of source code:

#include<iostream.h>

struct temperature_node 
{
	int day;
	float temperature;
	temperature_node *next;
};

int day_counter = 0;

temperature_node *head_ptr;
temperature_node *current_ptr;

int get_temp(int days, float &temp);
void show_temps();
void remove_temps();
void add_temp(int days, float temp);
void move_c_to_end();

int main()
{
	int days;
	float temp;

	cout << "enter the days for which you have data ";
    cin >> days;

	if(get_temp(days, temp))
	{
		head_ptr = new temperature_node;
		head_ptr->day = day_counter;
		head_ptr->temperature = temp;
		head_ptr->next = NULL;
	while(get_temp(days, temp))
		{
			add_temp(days, temp);
		}
	show_temps();
	remove_temps();
	}
return 0;
}

int get_temp(int days, float &temp)
{
	int keep_data = 1;

    if(day_counter == days)
	{
		keep_data = 0;
	}
	else
	{
		days = day_counter + 1;
		cout << days;
		cout << "enter the temperature for day " << day_counter + 1 << endl;
		cin >> temp;
		day_counter++;
	}
	return(keep_data);
}

void add_temp(int days, float temp)
{
	temperature_node *new_rec_ptr;
	new_rec_ptr = new temperature_node;

	new_rec_ptr->day = days;
	new_rec_ptr->temperature = temp;
	new_rec_ptr->next = NULL;

	move_c_to_end();
	current_ptr->next = new_rec_ptr;
}

void move_c_to_end()
{
	current_ptr = head_ptr;

	while(current_ptr->next != NULL)
	{
		current_ptr = current_ptr->next;
	}
}

void show_temps()
{
	current_ptr = head_ptr;

	do
	{
		cout << current_ptr->day << "         ";
		cout << current_ptr->temperature << endl;
		current_ptr = current_ptr->next;
	} while(current_ptr != NULL);
}

void remove_temps()
{
	temperature_node *temporary_ptr;

	current_ptr = head_ptr;

	do
	{
		temporary_ptr = current_ptr->next;
		delete current_ptr;
		current_ptr = temporary_ptr;
	}while(temporary_ptr != NULL);
}

Thanx :)

Member Avatar


1o0oBhP

4



Posting Pro in Training


18 Years Ago

I forgot to add current_ptr = current_ptr->next;

Common linked list error. By discovering it at least you have learned something! im sure we were paying attention, but from experience i find that giving hints rather than complete solutions helps you to learn faster! — and that ive only had time to post VERY late at night and im too tired to wade through code lol :)

Member Avatar

18 Years Ago

Yeah the whole current pointer bit made me feel pretty stupid. :o Anyway the program is still not displaying the proper day. I really appreciate the help you have been giving me, and I just wanna say thanx. If you do not really want to go through my code that is cool because I think I’ll figure it out eventually, but if you do happen to go through it and find something you can give me a hint on that’s even cooler :) I now can only get the last day to display and not any of the others.

thanx again

Member Avatar


1o0oBhP

4



Posting Pro in Training


18 Years Ago

I dont understand the confusing days and day_counter code. It seems a little overcomplicated.

What about using a for loop:

temperature_node *header = NULL;
temperature_node *current = NULL;

temperature_node t = new temperature_node; // new node
t.day = -1; // make the header day -1 to differentiate it from the main list

header = current = &t; // point header, current = header at the moment

cout << "Enter the number of days for which you have data";
cin >> days;

for(int i = 0; i < days; i++)
{
    temperature_node t = new temperature_node; // make a new node
    t.day = i; // set day
    current->next = &t; // link this to the current node
    cout << "Enter Temperature";
    cin >> t.temperature;
}

float temp;

current = header;
while(current != NULL)
{
    current = current->next;
    temp += current->temperature;
}

temp /= days;

cout << "Average temperature = " << temp;

its not tested, its straight off the top of my head. Should work though….


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

See more:

Hello,

What is the problem in this code

What does it mean ???

I have copied this code from layers_id_colors_and_visibility.h

error C2447: ‘{‘ : missing function header (old-style formal list?)
error C2017: illegal escape sequence
error C2017: illegal escape sequence
error C2017: illegal escape sequence
error C2017: illegal escape sequence
error C2017: illegal escape sequence

———————————————————

#define DECLARE_LAYERS_ORDER_LIST(list) int list[LAYER_COUNT] =
{   LAYER_N_FRONT,
    LAYER_N_15, LAYER_N_14, LAYER_N_13, LAYER_N_12,
    LAYER_N_11, LAYER_N_10, LAYER_N_9, LAYER_N_8,
    LAYER_N_7, LAYER_N_6, LAYER_N_5, LAYER_N_4,
    LAYER_N_3, LAYER_N_2,
    LAYER_N_BACK,
    ADHESIVE_N_FRONT , ADHESIVE_N_BACK,
    SOLDERPASTE_N_FRONT, SOLDERPASTE_N_BACK,
    SILKSCREEN_N_FRONT, SILKSCREEN_N_BACK,
    SOLDERMASK_N_FRONT, SOLDERMASK_N_BACK,
    DRAW_N,
    COMMENT_N,
    ECO1_N, ECO2_N,
    EDGE_N,
    UNUSED_LAYER_29, UNUSED_LAYER_30, UNUSED_LAYER_31
};

Понравилась статья? Поделить с друзьями:
  • Error c2440 function style cast
  • Error c2429 для функция языка структурированные привязки нужен флаг компилятора std c 17
  • Error c2415 недопустимый тип операнда
  • Error c2374 i redefinition multiple initialization
  • Error c2365 c