Why can't my program show Fibonacci series? - c++

My program can not show Fibonacci series but I think the code is right does anyone know why?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
using namespace std;
int main()
{
int a=0,b=1,c;
cout << "Fibonacci number" << endl;
cout << a << " ";
cout << b << " ";
while (c<100)
{
c=a+b;
a=b;
b=c;
}
cout << c << " ";
return 0;
}

There are two errors in your code, as already stated in the comments by someone else.
First, you are trying to use c without initializing it. Remember that in C++, when declaring a built-in type without initializing it, it is 'default initialized'. In other words, if you declare a variable of built-in type inside a function (in this case the main() function), it's value is undefined. Thus, you can't use it to check for a condition before assigning a value to it, and this is precisely what your while loop does.
Second, you are only pushing into the ostream the last calculated value of c. In other words, you are only printing the last value of you Fibonacci sequency.
Try putting your cout << c statement inside your loop.
PS.: Use the C++ version of C libraries whenever possible (i.e. <cstdio> instead of <stdio.h>, etc)

Related

invalid conversion from 'void*' to 'Guess*' [-fpermissive] from trying to realloc a structure

I am trying to program my own hangman game without refrencing other programs as a way to get back into programming.
Right now I am trying to program a structure that will hold all of the letters that will be alphabetized and displayed for the user. In the middle of trying to realloc i got this error
34 67 C:\Users\hanna\Documents\C Codes\Testing Hangman.cpp [Error] invalid conversion from 'void*' to 'Guess*' [-fpermissive]
Here is the code I am working with right now:
#include <ctime>
#include <stdio.h>
#include <iostream>
#include<stdlib.h>
#include <cstdlib> //has rand function
using std::cout;
using std::cin;
struct Guess {
char Letter[1];
};
int count = 0;
struct Guess*guessKeeper;
int main()
{
char choice;
cout << "Do you want to add another guess? \n";
cin >> choice;
cout << choice << "\n";
if (choice == 'y')
{
struct Guess newGuess;
cout << "What is your guess? \n";
cin >> newGuess.Letter;
guessKeeper = realloc(guessKeeper,(count+1)*sizeof(struct Guess));
count++;
guessKeeper[count-1] = newGuess;
cout << "Do you want to add another guess? \n";
cin >> choice;
};
free(guessKeeper); //Free Memory
}
Any recomendations on how to alphabetize would also be appretiated.
I have tried refrencing other online tutorials and some of my old code from my college classes; it is why I landed on structures as I have an old assignment that had used a structure and has code for alphabetizing I was hoping to refrence.
In C++ opposite to C you may not assign a pointer of the type void * to a pointer to an object type. You need to cast the return value of calls of for example realloc or malloc to the destination pointer type.
For example
guessKeeper = static_cast<Guess *>( realloc(guessKeeper,(count+1)*sizeof(struct Guess)) );
And in C++ you should use operators new and delete instead of realloc and free,
Also these statements in the end of the if statement
cout << "Do you want to add another guess? \n";
cin >> choice;
does not make sense because there is no loop in the program.
And this semicolon that defines a null-statement
//...
};
is redundant. Remove it.
And leave only the second include among these two includes
#include<stdlib.h>
#include <cstdlib> //has rand function
And remove this include
#include <stdio.h>
Also as correctly pointed #Blindy this declaration of the data member of an array type with one element does not make sense
struct Guess {
char Letter[1];
};
because this statement
cin >> newGuess.Letter;
results in memory corruption. That is it will try to read a string instead of a single character.
Instead you could declare the structure like for example
struct Guess {
char Letter;
};

use an empty {} to initialize a vector is different?

I see some people tend to initialize a vector with an empty {}, and I wonder whether it is different from directly initialize with the default constructor?
for example:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> vec;
vector<int> vec2 {};
cout << sizeof(vec) << " " << sizeof(vec2) << endl; // 24 24
cout << vec.size() << " " << vec2.size() << endl; // 0 0
}
and I check its assembly code, and it shows that initializing a vector with an empty {} generate more code(https://godbolt.org/z/2BAWU_).
Assembly code screen shot here
I am quite new to C++ language, and I would be grateful if someone could help me out.
Using braces is value initialization. Not using them is default initialization. As somebody alluded to in the comments, they should generate the exact same code when optimizations are turned on for vector. There's a notable difference with built-in types like pointers and int; there default initialization does nothing, while value initialization sets them to nullptr and zero, respectively.

C++ Dumping stack trace to *.exe.stackdump

Was writing some code for an assignment to take integers as input and place them in an array to be printed.
I'm cleaning up all of my pointers as far as I can tell but I keep getting the runtime error:
1 [main] new 3444 cygwin_exception::open_stackdumpfile: Dumping stack trace to new.exe.stackdump
body of code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int array[10];
int * p = array;
int *readNumbers()
{
int i=0;
for(i=0;i<10;i++)
{
string number;
int numb;
cout << "enter digit " << i << " of 10" << endl;
getline(cin, number);
istringstream (number) >> numb;
array[i]=numb;
}
return p;
delete p;
}
void printNumbers(int *numbers,int length)
{
int i;
for(i=0;i<length;i++)
{
cout << i << " " << *(numbers+i) << endl;
}
}
and the main calling code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
extern int *readNumbers();
extern void printNumbers(int *,int);
int main()
{
int * q = readNumbers();
printNumbers(q,10);
delete q;
return 0;
}
So just looking for a solution to the stack dump...
Also I'm sure the method I used to apply the string number returned by cin to the values contained in array[10] is not what the question was looking for so any notes on that would be great.
Thanks
It is not a good practice to return a pointer to a memory allocated inside a function, in this case, you are not even allocating it inside a function, you have done it in a global space.
It is a good practice to activate all your warnings during the compile, even treat them as error when you are doing an assignment.
As a tip, you can allocate the memory in your main function and then pass the pointer to the readNumbers function.T This way it remains inside the same scope and it is easier to manage.
also, the same way you pass the lenght of the array to the printnumbers function you should pass it to the readnumbers one instead of hardcoding it.
Your delete are invalid, you can only delete something you've allocated with new.
The first one is harmless because it's after a return, so never executed (BTW you should look at compiler warnings).
The second one might produce your crash.
Also I'm sure the method I used to apply the string number returned by cin to the values contained in array[10] is not what the question was looking for so any notes on that would be great.
That's OK. What's dubious is spreading the size of the array everywhere, what happens if you want to change it ?

how can I make strptime work on a vector of struct tm in c++?

I'm working in a c++ application that read a csv file and stores the content in a matrix of doubles and in a vector of struct tm. I have something similar to this:
#include <iostream>
#include <time.h>
#include <vector>
using namespace std;
int main(){
vector<struct tm> tmTM;
strptime("20020202", "%Y%m%d", &tmTM[0]);
cout << tmTM[0].tm_year << endl;
cout << tmTM[0].tm_mday << endl;
cout << tmTM[0].tm_mon << endl;
return 0;
}
Unfortunly this code generate a error Segmentation fault (core dumped)
I'm a begginer in c++ so I don't know what is wrong with the code.
Thanks a lot!
The default constructor for a vector generates an empty vector. That means that any access to an element, even element [0], will result in undefined behavior.
The usual way to handle this is to work with a temporary variable, then use push_back to place the temporary into the vector.
struct tm temp;
strptime("20020202", "%Y%m%d", &temp);
tmTM.push_back(temp);

Offsetof Function with std::vector

Could someone explain to me why the offsetof function does not work on std::vectors as shown below:
#include <windows.h>
#include <iostream>
#include <vector>
using namespace std;
struct FooStruct {
double x;
double y[10];
std::vector<double> z;
};
int main() {
cout << offsetof(FooStruct, x) << endl;
cout << offsetof(FooStruct, y[2]) << endl;
cout << offsetof(FooStruct, z[2]) << endl;
system("Pause");
}
Calling offsetof(FooStruct, z[2]) produces the following compiling error:
cannot apply 'offsetof' when 'operator[]' is overloaded
offsetof(FooStruct, z[2]) makes no sense. The elements of z are not contained within a FooStruct, they're accessed via the std::vector, which has at its core a pointer to some other allocation on the heap within which z[2] can be found.
In any case, the error (which seems confusing I understand) is probably popping up because std::vector overloads operator[], not because your class FooStruct overloads operator[] (which, assuming we see the whole definition, it doesn't).
If you want to find the offset of z[2] in relation to z[0], you could just compute the difference between &z[0] and &z[2] like this: std::cout << (&z[2] - &z[0]) << '\n';
Because offsetof isn't a function but a macro, and only works on POD types, or standard layout class in C++11. It's only there for backward compatibility with C.
The reason the compiler refuses to allow you to use the subscription operator, all issues aside, is because the macro is evaluated at compile time, but the overloaded operator might do some work at runtime to calculate the result.