如何从文件输入,然后在c++中同时使用标准i/o流
How to input from file then use standard i/o stream simultaneous in 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
是问题所在,程序停止工作。
你的问题不在中国>> 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);
}
相关文章:
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 无法将标准库导入本机 android 项目中的头文件
- 从标准输入读取文件后读取用户输入
- CMake 不编译具有非标准扩展名的文件
- Windows 将标准的 C 文件结构注入到正在运行的进程中
- MacOS 上的 LLVM - 标准文件 iosfwd 中未知类型名称'template'
- 张量流错误 此文件需要编译器和库支持 ISO C++ 2011 标准
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- C++标准视窗 SDK 文件中的编译错误
- 猫鼬 - 包含标准C++库文件时出错
- 在Qt中链接具有非标准名称的lib文件
- 是否有一个标准函数可以打印/监视stdin文件的内容,同时将数据留在stdin中
- 读取二进制文件的惯用C++17标准方法是什么
- 如何比较time_t和标准::文件系统::file_time_type
- 是否有标准的文件保存和交换模式
- 在 ubuntu 上安装 c++ 标准库文件
- 如何减小C++标准库libstdc++.so文件大小
- #include 多个.cpp中的标准文件,与将其 #include 在预编译标头中会影响可执行文件的大小?
- 如何将字符串转换为标准C文件
- 告诉gdb跳过标准文件