我想从一个文件中获取一些整数,然后从用户那里获取一个数字,但是当代码到达给出用户程序数字的行时,停止工作并退出 这是我的代码
#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
是问题所在,程序停止工作。
最佳答案
你的问题不在 cin >> l;
问题出在您的 mysearch 函数中。
你的算法是错误的。
在二进制搜索中,您不能使用 vector 大小的方法。相反,您应该使用 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);
}
关于c++ - 如何从文件输入然后在 C++ 中同时使用标准 i/o 流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313949/