终端"休息"?

时间:2015-09-22 02:06:41

标签: c++ ubuntu

我在Ubuntu中编写这个C ++程序时遇到了一个不寻常的情况。

该计划:

#inclue <iostream>
#include <string>
using namespace std;

void sizeOfTest() {
  int i = 27;
  unsigned int u = 14;
  float f = 3.14;
  double d = 2.71;
  char c ='c';
  bool b = true;
  int* n = &i;
  char* h = &c;
  double* o = &d;
  cout << "The size of int " << i << " is " << sizeof(i) << ".\n";
  cout << "The size of unsigned int " << u << " is " << sizeof(u) << ".\n";
  cout << "The size of float " << f << " is " << sizeof(f) << ".\n";
  cout << "The size of double " << d << " is " << sizeof(d) << ".\n";
  cout << "The size of char " << c << " is " << sizeof(c) << ".\n";
  cout << "The size of bool " << b << " is " << sizeof(b) << ".\n";
  cout << "The size of int* " << n << " is " << sizeof(n) << ".\n";
  cout << "The size of char* " << h << " is " << sizeof(h) << ".\n";
  cout << "The size of double* " << o << " is " << sizeof(o) << ".\n";
}

void outputBinary(unsigned int n) {
  string s = "";
  while (n != 0 || s. length() != 32) {
    if (n%2 == 1) {
      s = "1" + s;
      n = (n-1)/2;
    }
    else {
      s = "0" + s;
      n = n/2;
    }
  }
  cout << s.substr(0,4) << " " << s.substr(4,4) << " " << s.substr(8,4) << " " << s.substr(12,4) << " " << s.substr(16,4) << " " << s.substr(20,4) << " " << s.substr(24,4) << " " << s.substr(28,4) << " ";
}

void overflow() {
  unsigned int m = 65535;
  cout << (m+1);
}

int main() {
  unsigned int x;
  cout << "Please enter an integer:";
  cin >> x;
  sizeOfTest();
  outputBinary(x);
  overflow();
  return 0;
}

输出: enter image description here

所以我的问题是:

  1. 为什么我的换行不起作用? (它们的格式与cout函数中sizeOfTest行的格式完全相同。)
  2. 即使在h文件之外,当我调用a.out导致所有以下字符中断时,会发生什么?我该如何解决这个问题?
  3. 非常感谢你!

1 个答案:

答案 0 :(得分:1)

ostream插入器假设char *参数将指向空终止字符串。这里情况不同。所以它会从内存中写入垃圾,直到遇到内存中的0x0字符。

如果您只想打印c的地址,请将h投放到void *

cout << "The size of the address " << (void *)h << " is " << sizeof(h) << "." << endl;

关于换行符,您可以尝试将"\n"替换为std::endl。我不认为你说过你所使用的终端或操作系统,但终端可能会混淆&#34; \ n&#34;的含义。 (不应该,但如果这是在cygwin上的Windows上的gcc或者其他什么,谁知道。)