c++ - 多位数拆分为单位数的数组输入(线性搜索)
问题描述
#include <iostream>
using namespace std;
template <class T> class Linear {
private:
T *a;
T key;
int n;
public:
Linear();
void LS();
};
template <class T> Linear<T>::Linear() {
a = new T[10];
cout << "\nEnter the no. of elements in the array";
cin >> n;
cout << "\nEnter the elements in the array";
for (int i = 0; i < n; i++) cin >> a[i];
cout << "\nEnter the key value";
cin >> key;
}
template <class T> void Linear<T>::LS() {
int flag = 0, i;
for (i = 0; i < n; i++) {
if (key == a[i]) {
flag = 1;
break;
}
}
if (flag == 1) cout << "\nElement found at" << i + 1 << "index";
else cout << "\nElement not found";
}
int main() {
Linear<char> l;
l.LS();
return 0;
}
该代码旨在将多个数字读入数组。但是,当我输入
5 23 24 25 26 27
我期待看到
23 24 25 26 27
但我明白了
2 3 2 4 2
解决方案
问题(感谢@brc-dd 澄清)是cin
关于 char 类型的行为与直觉相反。它一次只读取一个字符,而不是将 char 视为在所有其他方面都是数字的数字。下面的代码演示了这个事实
#include <iostream>
#include <stdint.h>
#include <sstream>
using namespace std;
int main(){
std::stringstream ss("27");
int8_t v_int8;
char v_char;
int v_int;
long v_long;
short v_short;
ss >> v_int8;
std::cout << v_int8 << std::endl;
ss.seekg(0);
ss >> v_char;
std::cout << v_char << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_int;
std::cout << v_int << std::endl;
ss.seekg(0);
ss >> v_short;
std::cout << v_short << std::endl;
ss.seekg(0);
ss >> v_long;
std::cout << v_long << std::endl;
ss.seekg(0);
}
输出是
2
2
27
27
27
27
请注意,即使您尝试变得聪明并使用int8_t
它,它实际上也只是一个别名,char
并且会逐个字符读取,而不是您可能假设的数字。
注意:stringstream
就像使用cin
除了输入来自字符串而不是用户输入。ss.seekg(0)
只是将流放回字符串的开头。
推荐阅读
- c# - 基于无效模型测试 BadRequest 结果
- c - 对如何在 makefile 中包含/编译依赖项感到困惑
- python - 如何找到数值时间序列的多个最大值
- pointers - 我可以使用指针以什么粒度访问主内存?
- mysql - 在 Jooq 中集成 Hikari 池
- python - 在带参数的数据框中使用应用会返回错误
- javascript - 在 Django 中,如何在单击鼠标后从预览中显示更多数据?
- r - 如何在 checkboxGroupInput 中使用下载数据集中的变量
- android - 更改屏幕动画的开始
- arduino - 为什么我不能用 AT 命令降低 ESP8266 的波特率