首页 > 解决方案 > 多位数拆分为单位数的数组输入(线性搜索)

问题描述

#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

标签: c++search

解决方案


问题(感谢@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)只是将流放回字符串的开头。


推荐阅读