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

标签 c++ fstream

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

#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/

相关文章:

java - 接受右值引用作为参数的方法的 Swig 行为

c++ - 尽管覆盖仍编译错误

c++ - 神秘的相对路径库依赖

c++ - 我需要帮助了解如何在 C++ 中对包含多个带空格的字符串的集合或 vector 进行排序

c++ - 一次又一次尝试在给出错误路径的同时打开文件

c++ - 想逐行阅读,但 fstream 只读第一行

c++ - 如果抛出的值匹配多个 catch 子句会发生什么?

c++ - SDL C++ IDE 无法打开 .ttf 文件

c++ - 不确定如何解决 'std::out_of_range' 错误

c++读取txt文件并复制到两个类istream::peek()