How to initialize this array in a clean way? - c++

I am trying to initialize this array in C++ :
C++
#include<iostream>
using namespace std;
int main(){
int arr[100];
int i = 10;
while(i){
cin >> arr[--i];
}
return 0;
}
This initializes the array perfectly, but it returns a negative status. How can I solve it?

The status code means the program didn't get to the last line of your main() function (where it should be return 0), but got killed instead. I guess you just stopped it with CTRL+C.

Related

What is the problem with the following code using constructors for sorting strings?

#include <iostream>
#include <string.h>
using namespace std;
class sorting
{
private:
char str[10];
public:
sorting() {
int i;
for(i=0;i<10;i++) {
cin>>str[i];
}
}
void sort() {
int i,j;
char temp;
for(i=0;i<10;i++) {
for(j=i+1;j<10;j++) {
if(strcmp(str[j],str[j+1])>0) {
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
for(i=0;i<10;i++) {
cout<<str[i];
cout<<"\n";
}
}
};
int main() {
sorting s1;
cout<<s1.sort();
return 0;
}
This is a code I have written to sort strings using constructors. It gives me error in the if condition of the code where I have used strcmp. Please review this for I could not get the desired output and it gives me errors.
Problem 1
Like someone already pointed out, you cant use strcopy on chars. If you want to create a string array i would suggest using either char** or std::string*.
Problem 2
In your nested loop you will get an index out of bounds error, due to the fact that once i reaches a value of 8, j will be 9, which means that when you try to access str[j+1] which evaluates to str[10], you will get said error.

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.

My C++ Program isn't executing my cout code

I am learning C++, and I am trying to make a simple program which prints 5 variables, as my book said to do this, but it is not executing my code.
#include<iostream>
using namespace std;
int main()
{
//Program Code below
return 0;
char letter; letter = 'A'; //Declared, then initialized
int number; number = 100; //Declared, then initialized
float decimal = 7.5; //Declared AND initialized
double pi = 3.14159; //Declared AND initialized
bool isTrue = false; //Declared AND initialized
cout<<"Char letter: "<<letter<<endl;
cout<<"Int number: "<<number<<endl;
cout<<"Float decimal: "<<decimal<<endl;
cout<<"Double pi: "<<pi<<endl;
cout<<"Bool isTrue: "<<isTrue<<endl;
}
As soon as your code executes this line
return 0;
no other lines of your code will be executed - from a practical point of view, your program will have ended. Move this line down so that it is the last line of code executed by your main() function.
Your problem is that you are returning from main before doing anything:
int main()
{
return 0; // HERE!!
// no code after return gets executed
}
Your return 0; should be at the end of main, not the start
Please re-position the "return 0;" statement
Since main is a function that returns an integer, the execution of the main function is primarily to return some integral value. As soon as the value is returned, the function assumes its job is complete and hence does no longer hold the control of the program.
Your code:
#include<iostream>
using namespace std;
int main()
{
return 0; // Function thinks its job is done hence it ignores everything after it.
...some other code
}
Actually what you wish to do:
#include<iostream>
using namespace std;
int main()
{
... useful code
return 0; // Okay. Returning is alright, as the useful job is done.
}

C++ program has stopped working

I am making a quite simple program, just a little chat bot AI kind of thing, and I have some code, c++ of course, for the program. I don't get any errors but when I run it a window comes up saying program.exe has stopped working, like it stopped responding. My code is:
#include<iostream>
#include<string.h>
#include<cmath>
#include<vector>
#include<ctime>
#include<conio.h>
#include<algorithm>
#include<cstdlib>
using namespace std;
struct strarray{
char* array[];
};
struct keyword{
string keywords;
string responses[];
};
keyword * dictionary = new keyword[2];
keyword defaultr;
keyword getMatch(string key);
string sconvert(string con);
void init();
string getResp(keyword key);
bool cont=true;
int main(int argc, char* argv[]){
string input;
while(cont){
getline(cin,input);
cout << getResp(getMatch(input));
getch();
getch();
}
}
string sconvert(string con){
con.erase(remove_if(con.begin(), con.end(), ::isspace), con.end());
con.erase(remove_if(con.begin(), con.end(), ::ispunct), con.end());
return con;
}
void init(){
srand(time(NULL));
dictionary[0].keywords="hello";
dictionary[0].responses[0]="Hello, how have you been?";
dictionary[0].responses[1]="Hello, have you missed me?";
dictionary[0].responses[2]="Hey, how's it going?";
defaultr.responses[0]="That's interesting, tell me more.";
defaultr.responses[1]="Please, tell me more.";
}
keyword getMatch(string key){
for(int i=0; i<sizeof(dictionary); i++){
if(key==dictionary[i].keywords){return dictionary[i];}
}
return defaultr;
}
string getResp(keyword key){
return key.responses[rand() % sizeof(key)];
}
When I run it, it opens up normally, but after I input something when it comes up it "stops working". Could somebody please tell me what I need to change, and why would be appreciated.
Is there some pointer problem? Or something with the rand? I'm really confused and would appreciate some advice on how to better this program so it actually works.
sizeof(dictionary) will give sizeof(keyword*), probably 4 or 8, so you will iterate over the end of the dictionary array and terminate.
Easiest fix: Define a constant to store the array length.
const dictionarySize = 2;
and use that throughout.
You also need to change struct keyword to:
struct keyword{
string keywords;
string responses[3];
};
first of all u have an infinite loop so the program should work for ever .. I took a glance at the code and using rand() % sizeof(key) is wrong, the responses is not predetermined so either you set it to a specific value for example
struct keyword {
string keywords;
string responses[2];
};
rand() % sizeof(key.responses)
or you make your structure like this
struct keyword {
string keywords;
vector<string> responses;
};
rand() % key.responses.size()
//After setting the responses by push_back for example
there are other ways but this is safer and no memory management needed ...

why std::map throws an exception?

I run this code using both gpp and microsoft compiler but in both case I'v got an exception
but I can't understand why!
this is my code:
#include <iostream>
#include <map>
using namespace std;
map<int,int> fib;
int fibo(int i)
{
if (!fib.count(i))
{
fib.insert(pair<int, int>(i,fibo(i-1)+fibo(i-2)));
}
return fib[i];
}
int r(int i)
{
if(i<3)
{
return i;
}
else
{
return fibo(i)+r(i-2);
}
}
int main()
{
fib.insert(pair<int, int>(0,1));
fib.insert(pair<int, int>(1,1));
int a,b,n;
cin>>a>>b;
n=b-a;
int fiba=fibo(a);
int fibaa=fibo(a-1);
cout << (r(n+1)*fiba)+(r(n)*fibaa);
return 0;
}
can anyone help me?
I debugged this code and I found that fib.insert(pair<int, int>(i,fibo(i-1)+fibo(i-2))); doesn't work.
I've got Stack Overflow exception when I ran your code, obviously because of too deep recursion.
You should either increase stack size (but you can later choose to input a larger number and get the same exception again), or convert this algorithm into a non-recursive one (for example see this one: http://www.codeproject.com/Tips/109443/Fibonacci-Recursive-and-Non-Recursive-C)
Did you try to input some negative numbers? You don't do any check on the inputs you pass to your program, and in
return fib[i];
you will receive an error if you try to access non-existent locations.