2016-10-28 6 views
0

나는 파일에서 약간의 정수를 얻기 위해 원하는 그 후 사용자의 숫자를 얻을 수 있지만, 코드가 사용자 프로그램 정지 작업에서 수를 제공 라인에 도달 을 얻을 때 이것은 내 코드파일에서 입력 한 다음 표준 I/O 스트림을 C++에서 동시에 사용하는 방법?

#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; 
} 

입니다 cin>>l은 문제가 있고 프로그램이 작동을 멈추는 곳입니다.

+0

'beep.size()'를'int'로 변환 할 필요는 없습니다. 이미 정수입니다. – Barmar

+0

재귀 호출을 할 때'return mysearch (...) '를 사용해야합니다. – Barmar

+0

정렬 기능이 작동하지 않습니다. '3 1 5 10 11 50' – Barmar

답변

0

당신의 문제는 cin >> l이 아닙니다;

문제는 mysearch 기능에 있습니다.

알고리즘이 잘못되었습니다.

이진 검색에서는 벡터의 크기를 사용할 수 없습니다. 대신 top과 bot (코드에서)을 사용해야합니다. 당신에게 다른 문제가 있습니다.

이 코드를 살펴보십시오.

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); 
}