Input crash (C++) - c++

Hello i've written a code, but if i want to run the code after i've inputted the code it just crashes.
The program should pick the first 10 out of a vector, pick the highest one and destroy everything before that and refill it until it's ten long again.
I've used a for loop to do this. I've just started with this like 2 months.
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
int Aantal;
cin >> Aantal;
vector<int> F(Aantal);
for(int i=0; i<Aantal; i++)
{
cin >> F[i];
if(Aantal>1000)
{
cerr << "You're above 1000" << endl;
return -1;
}
if(Aantal<20)
{
cerr << "You're below 20" << endl;
return -1;
}
if(i>Aantal)
{
cerr << "Not above 'Aantal'" << endl;
return -1;
}
if(i<0)
{
cerr << "Not smaller than 0!" << endl;
return -1;
}
}
for(int z=0; z<Aantal; z++)
{
if(z == 0){
int a = 0;
}
int a;
vector<int> arr(F.begin()+a, F.begin()+10+a);
int c = *max_element(arr.begin(), arr.end());
cout << c << endl;
vector<int>::iterator q;
q = find(arr.begin(), arr.end(), c);
int pos = distance(arr.begin(), q);
arr.erase(arr.begin(),arr.begin()+pos);
int a1 = 10-arr.size();
int b = a+a1;
a = b;
if(a+10>Aantal)
{
break;
}
arr.erase(arr.begin(), arr.end());

Your problem is here:
int a;
vector<int> arr(F.begin()+a, F.begin()+10+a);
You create a variable a, never initialize it and then you use it to construct the vector. Since a has a garbage value this is going to mess up the vector creation as more than likely you will be getting the wrong positions.
I am not sure what you are doing right before that with:
for(int z=0; z<Aantal; z++)
{
if(z == 0){
int a = 0;
}
As all this does is set a to zero and then you discard a as it was declared in the if block.

Related

Finding Max, Min and Mode in c++

So basically I am trying to write a program which accepts an array of integers and then outputs the Max Min and smallest Mode and how many times it occurs.
I have been able to find both max and min and mode, but instead of the smallest mode my code outputs the one that occurs first. And i am not sure how to handle an input with more than one mode.
Below i’ll post my code:
#include
using namespace std;
int main() {
int p,max,min,mode;
cout << "Enter the number of postive integers:"<< endl;
cin >> p;
int pos[p];
cout << "Now enter postive integers!" <<endl;
for(int i=0; i<p; i++) {
cout << "Positive integer " << i+1 << ":";
cin >> pos[i]; }
max =pos[0];
min =pos[0];
for( int i=0; i<p; i++){
if(pos[i]> max) max=pos[i];
if(pos[i]< min) min=pos[i];
}
cout << "Max=" << max << endl;
cout << "Min=" << min << mode= pos[0];
int count[20];
int t=0;
for(int c=0;c<p; c++)
{
for(int d=0;d<p;d++)
{
if(pos[c]==pos[d])
{
count[c]++;
t++;
}
}
int modepos, maxno=count[0];
for(int e=1;e<p;e++)
{
if(maxno<count[e])
{
maxno=count[e];
modepos=e;
}
}
mode=pos[modepos];
if(t==1) {
cout << "There is no positive integer occuring more
than once." << endl;
}
else {
cout <<"The most occuring positive integer is:"<< mode;
cout << "\nIt occurs " << t << " times." << endl;
} return 0; }
there may be simpler and better ways to code this but since i’m a beginner and have only learned loops/conditionals/arrays/variable declaration etc I can only use them in the program, any help will be appreciated.
Do you learn about std::map? The algorithm for counting how many times of an element on an array is very simple with std::map
std::map<long, long > mapFreq;// first: for store value of array pos, second for store value's counter
mapFreq.insert(std::pair<long, long>(pos[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(pos[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(pos[i], 1));
}
}
Then you can loop through map Freq for what you need:
int number, counter;
for(auto it : mapFreq)
{
if(it.second < counter)
{
number = it.first;
counter = it.second;
}
}
Maybe you can try doing this:
#include <iostream>
#include <algorithm> //for sorting
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[n];
sort(a,a+n);
int b[a[n-1]];
for(int i=0;i<a[n-1];i++) b[i]=0;
for(int i=0;i<n;i++) b[a[i]]++;
cout<<"Largest number = "<<a[n-1]<<endl;
cout<<"Smallest number = "<<a[0]<<endl;
int rep=0;//repetition
int mode=0;
for (int i=0;i<a[n-1];i++){
if(b[i]>rep){
rep=b[i];// set times of repetition
mode=i;// set new mode
}
}
cout<<"Mode = "<<mode<<endl;
}

Controlling input in c++ and display

Question :
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Example
Input:
1
2
88
42
99
Output:
1
2
88
So that is the question, however i am still a beginner and unable to have an input tab like that. In my program, how should i modify it such that it still accepts numbers after 42, however, it does not print them? currently I am only able to terminate the input at 42.
#include <iostream>
using namespace std;
int main()
{
int A[100], num, i=0,k,count;
for(count = 0; count != 1;){
cin >> k;
if (k!=42){
A[i] = k;
i++;
}
else
count =1;
}
cout << endl;
for (count = 0; count <i; count ++){
cout << A[count] << endl;
}
}
You don't have to use array at all. You can print the value just after reading it. Exit when you read 42. This may help you.
#include <iostream>
using namespace std;
int main() {
// your code goes here
int n ;
for(; ;) {
cin >> n ;
if(n == 42) {
return 0 ;
}
cout << n << endl ;
}
return 0;
}
Pretty sure the easiest way to do so is to simply ask the user how many numbers they need to enter.
#include <iostream>
using namespace std;
int main()
{
int A[100], k, count;
cout << "How many numbers do you want to enter ? ";
cin >> count; //this is to count how many numbers the user wants to enter
for(int i(0); i < count; ++i) //put all the numbers user enters in your array
{
cin >> k;
A[i] = k;
}
cout << endl;
for (int i(0); i < count; ++i)
{
if (A[i] == 42) //if the element at index i is == 42 then stop displaying the elements
break;
else
cout << A[i] << " "; //else display the element
}
cout << endl;
return 0;
}
Else you would need to put everything in a string and parse it and i'm not quite sure how that goes as I am a beginner as well.
EDIT:
Actually here you go, I think that is correct and does exactly what you want.
Do keep in mind that if user enters p.e "1 88 442" it will output "1 88 4" because it found "42" in "442". But it should be okay because you precised input numbers should only be two digits max.
#include <iostream>
using namespace std;
int main()
{
string k;
getline(cin, k);
cout << endl;
for (unsigned int i(0); i < k.length(); ++i)
{
if (!((k[i] == '4') && (k[i+1] == '2'))) //if NOT 4 followed by 2 then display
cout << k[i];
else
break; //else gtfo
}
cout << endl;
return 0;
}
Use a bool value to control the execution of your code.
#include <iostream>
#define N_INPUT 100
#define THE_ANSWER 42
using namespace std;
int main()
{
int array[N_INPUT], i, input, count=0;
bool universeAnswered = false;
for (i = 0; i < N_INPUT; i++) {
cin >> input;
if (!universeAnswered)
{
if (input == THE_ANSWER) {
universeAnswered = true;
} else {
array[count] = input;
count++;
}
}
}
for (i = 0; i < count; i++) {
cout << array[i] << endl;
}
}
(My code was not tested)
You just have to have some state to see if you have seen 42 already, and only output if you haven't
#include <iostream>
int main()
{
bool output = true;
for (int n; std::cin >> n;)
{
output &= (n != 42);
if (output)
{
std::cout << n << std::endl;
}
}
return 0;
}

Where is the Error in my C++ code?

Here is the error screenshot: http://prntscr.com/9n6ybt
Here is the code:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{
if (b%i==0)
{
cout << i << " ";
}
}
return 0;
}
for(int i=a;i<=b;i++)
{
if (b%i==0)
{
cout << i << " ";
}
}
Will give a division by zero if i == 0.
You'll have to check the input, or the value of i, for example:
for(int i=a; i<=b; i++)
{
if (i > 0 && b%i==0)
{
cout << i << " ";
}
}
If i == 0, b%i==0 will not be evaluated.
You are not handling the case where i might be 0 (division by 0) so b % i is indetermined. You can solve it by going this way:
if (i==0) continue;
You should handle the case division by "zero". When the value of i = 0 then the code fails and produce an exception.
You should do like this:
#include <iostream>
using namespace std;
int main()
{ int a, b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{ if (i == 0)
continue;
else if (b%i == 0)
cout << i << " ";
}
return 0;
}

how to save the sorted arrays in textfile?

I have a program that sorted arrays how can i save in text file?
for example: the sorted arrays is: 1, 2, 3, 4, 5.
how can i save in text file named. Sorted elements".
I've tried many ways but the sorted array wouldn't save in text file.
I am a newbie so I find it difficult.
here is my code.
#include <iostream>
using namespace std;
int main() {
cout << "Enter number of element:";
int n; cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cout << "element number " << (i+1) << " : ";
cin >> a[i];
}
int e=1, d=3;
int i, j, k, m, digit, row, col;
int length = sizeof(a)/sizeof(int);
int bmat[length][10];
int c[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
cout << endl;
cout << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
cout << a[i] << " , ";
}
cout << endl;
system("pause");
return 0;
}
//Use this code
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter number of element:";
cin >> n;
//Data Structure
std::vector<int> list;
//push back element in vector
for(register int i=0;i<n;++i)
list.push_back(rand()%10 + 1);
//do shuffling before sorting because rand() generates increasing order number
std::random_shuffle(list.begin(),list.end());
std::sort(list.begin(),list.end());
ofstream textfile;
textfile.open ("E:\\example.txt");
for(size_t i= 0;i<list.size();++i)
textfile << list[i] <<" ";
textfile.close();
}
If you can write the sorted array to std::cout, then you can write it to a file. In C++, the console is the same as a file.
Put this at the end of main:
cout << "Sorted array:" << endl;
print_array( std::cout, a, n ); // Show the results to the user.
std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
print_array( save, a, n ); // Save the results for later.
system("pause");
return 0;
}
and put the printing code in a new function, which may be defined before main:
void print_array( std::ostream & s, int * a, int n ) {
for(int i=0;i<n;i++)
{
s << a[i] << " , ";
}
s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
return(x > y);
}
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void display(int array[], int n){
for (int i = 0; i<n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void writeToFile(int array[], int n){
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
}
void sort(int table[], const int n) {
for (int i = 0; i < n; i++){
for (int j = 0; j < n - 1; j++) {
if (compare(table[j], table[j + 1]))
swap(&table[j], &table[j + 1]);
}
}
}
int main(){
int quantity;
int* tab;
ofstream outfile;
cout << "Enter number of element: ";
cin >> quantity;
tab = new int[quantity];
cout << "Element:\n\n" << endl;
for (int i = 0; i < quantity; i++){
int x = i;
cout << "#" << ++x << ":";
cin >> tab[i];
}
sort(tab, quantity);
cout << "The Sorted Elements are: ";
display(tab, quantity);
writeToFile(tab, quantity);
cout << endl;
getchar();
getchar();
//system("pause");
return 0;
}
in short, add this block to your code:
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
You can use C++ fstream class, since you want to output, you can use ofstream here. You should just replace some "cout" with ofstream instance:
At the beginning of the code state it:
ofstream ofs("./sorted_elem.txt", ofstream::out);
When want to output:
ofs << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
ofs << a[i] << " , ";
}
ofs << endl;
In C++ you really want to use std::vector or some other nice container for storing arrays of numbers. For writing an array to file you need to open the file and individually write each element to the file (all untested).
#include <fstream>
int main()
{
std::ofstream fp("output.txt");
int data[5]; // todo: fill
for (unsitned i = 0; i < 5; ++i)
{
fp << data[i] << ' ';
}
}
And to read again:
#include <fstream>
int main()
{
std::ifstream fp("output.txt");
// todo: Determine the size of the array or guess it (don't guess it!)
unsigned array_size = 5;
int data[array_size];
int n = 0;
while (fp.good() && n < array_size) fp >> data[n++];
}
But because we are using C++, we can use std::vector:
#include <fstream>
#include <vector>
int main()
{
std::vector<int> me(5); // todo: fill
std::ofstream fp("output.txt");
for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
// C++11: for (int d : me) fp << d << ' ';
}
And,
#include <fstream>
#include <vector>
int main()
{
std::ifstream fp("output.txt");
std::vector<int> data;
double buf;
while (fp >> buf) data.push_back(buf); // no longer need to guess
}
I think, the copy option was not demonstrated here so far.
Please check this code. (Assuming your vector is ready to use, I've skipped it).
The example uses a C-array and a vector. Please use the later in your code whenever possible. But however, for copy-function both work:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
int main () {
int a[10]={0,1,2,3,4,5,6,7,8,9};
std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
std::ofstream fs_a( "c:/temp/out_a.txt" );
//store space separated
std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
//store coma-separated, as one-liner
std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
return 0;
}

Adding values to a vector until the user inputs 0 in C++?

How do I structure my while loop so that it will keep accepting int values until the user enter 0?
I have
while(cin >> integers && integers != 0){
numbers.push_back(integers);
if(integers == 0){
break;
}
}
but it keeps crashing on me.
Edit:
int integers;
int fox;
vector<int> numbers;
cout << "Please enter in integers (0 to stop): ";
while(cin >> integers){
numbers.push_back(integers);
if(integers == 0){
break;
}
}
int y = numbers.size();
for(int i = 0; i < y; y++){
cout << numbers.at(y) << " ";
}
y should be i. You're accessing the vector out-of-bounds. Also y++ should be i++, otherwise you will have an infinite loop.
for (std::vector<int>::size_type i = 0; i < members.size(); i++) {
cout << numbers.at(i) << " ";
}
operator[] does not have bounds checking, so at is actually a bit safer in this regard.
Visual Studio was probably either aborting because of your infinite loop, or because you had an out_of_range exception that went uncaught. For example, it might look like this:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
It is unnecessary, but you can wrap your code in a try-catch block.
try
{
std::cout << members.at(members.size());
} catch(std::out_of_range& ex)
{
std::cout << "Out of range error: " << ex.what() << "\n";
}
Here is an example based on your question.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
int integers;
while(cin >> integers && integers != 0){
numbers.push_back(integers);
}
for( int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i] << ' ';
return 0;
}
After seeing your edited question.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int integers;
int fox;
vector<int> numbers;
cout << "Please enter in integers (0 to stop): ";
while(cin >> integers){
if(integers == 0){
break;
}
numbers.push_back(integers); //Moved after the check to not inclue 0
}
int y = numbers.size();
for(int i = 0; i < y; i++){
cout << numbers[i] << " ";
}
return 0;
}