如何从文件输入,然后在c++中同时使用标准i/o流

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

本文关键字:标准 文件 输入 c++ 然后      更新时间:2023-10-16

我想从文件中得到一些整数,然后从用户那里得到一个数字,但是当代码到达从用户程序中给出数字的行时停止工作并退出这是我的代码

#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是问题所在,程序停止工作。

你的问题不在中国>> 1;

问题出在你的mysearch功能上。

你的算法是错误的。

在二分查找中,不能使用vector的size方法。相反,您应该使用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);
}