Ali Asghari
Ali Asghari

Reputation: 112

How to input from file then use standard i/o stream simultaneous in c++?

I Want to get some Integer from a file and after that get a number from user but when code reaches to the line that gives number from user program stop working and gets out this is my code

#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#include <fstream>
using namespace std;

void mysort(vector<int>& beep) //this is for sorting vector has no problem
{
    int temp;
    for (int i = 1; i < beep.size(); i++) {
        if (beep[i - 1] > beep[i]) {
            temp = beep[i];
            beep[i] = beep[i - 1];
            beep[i - 1] = temp;
        }
    }
}

int mysearch(vector<int>& beep, int x, int top, int bot) //and this is not problem too
{
    int mid = (top - bot +1) / 2;
    if (x == beep[mid])
        return mid;
    else if (x > beep[mid])
        return mysearch(beep, x, beep.size(), mid + 1);
    else
        return mysearch(beep, x, mid - 1, 0);
}

void myprint(vector<int>& beep) //and this is for printing have no problem
{
    for (int i = 0; i < beep.size(); i++)
        cout << beep[i] << " ";
}

int main()
{
    vector<int> beep;
    ifstream in;
    in.open("input.txt");
    int x;
    while (in >> x) {
        beep.push_back(x);
    }
    in.close();
    mysort(beep);
    int l;
    cout << "this is sorted array: " << endl;
    myprint(beep);
    cout << endl;
    cout << "enter which one you looking for: ";
    cin >> l; //this is where problem begins
    cout << mysearch(beep, l, beep.size(), 0);
    return 0;
}

In the cin>>l is where problem is and program stops working.

Upvotes: 1

Views: 53

Answers (1)

andercruzbr
andercruzbr

Reputation: 454

Your problema isn't at cin >> l;

The problem is in your mysearch function.

Your algorithm is wrong.

In a binary search, you can't use method size of a vector. Instead you should use top and bot (in your code). There is other problem in you function.

Look this code.

int search (int x, int v[], int left, int right)
{
    int i = (left + right)/2;
    if (v[i] == x)
        return i;
    if (left >= right)
        return -1;
    else
        if (v[i] < x)
            return search(x, v, i+1, right);
        else
            return search(x, v, left, i-1);
}

Upvotes: 1

Related Questions