jeudi 20 septembre 2018

What happens when c++ expects one data type and gets another?

I am new to c++ and was making a program in c++11 that sorts a list of integers using the bubble sort algorithm. While I was doing this I noticed something weird. This is my code:

#include <iostream>
void bubbleSort(int x) {
  bool done;
  int list[x] {0};
  std::cout << "List:\n";
  for (int i=0;i<x;i++) {
    std::cout<<i<<':';
    std::cin>>list[i];
  }
  do {
    done = true;
    for (int i=0;i<x-1;i++) {
      if (list[i]>list[i+1]) {
        list[i] = list[i]+list[i+1];
        list[i+1] = list[i]-list[i+1];
        list[i] = list[i]-list[i+1];
        done = false;
        }
    }
  } while (not done);
  for (int i:list) {
    std::cout<<i<<' ';
  }
  std::cout<<std::endl;
}
int main() {
  int n;
  std::cout<<"Length of list: ";
  std::cin>>n;
  bubbleSort(n);
} 

If I input a char instead of an int the program outputs numbers leading up to the length of the list then a string of zeros equal to length of the list.

ex: if I input 5 then k:

1:2:3:4:0 0 0 0 0 

My question is, why? I would expect an error if it gets the wrong data type. Sorry if my question is confusing. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire