2013-05-12 160 views
0

我有一個簡單的程序如下:爲什麼我的字符串在C++中打印不正確?

#include <iostream> 

using namespace std; 

int main() 
{ 
    int N; 
    cout << "Enter N: " << endl; 
    cin >> N; 
    int acc = 0; 

    cin >> acc; 
    int min = acc; 
    int max = acc; 


    for (int i=1; i<N; i++) { 
     int current; 
     cin >> current; 
     acc += current; 
     if (current > max) { 
      max = current; 
     } else if (current < min) { 
      min = current; 
     } 
    } 

    cout << "Total: " + acc << endl; 
    cout << "Max: " + max << endl; 
    cout << "Min: " + min << endl; 
    return 0; 
} 

我的輸出是越來越砍掉如下

./stat 
Enter N: 
3 
1 
2 
3 

: 
in: 

我在做什麼錯?

回答

4

在C++中,字符串和數字的運算符+的行爲與您對高級語言的期望不同。

「Total:」例如是字符數組,如果a[10]是您的數組,則a + 5是從a[5]開始的數組的切片。這就是所謂的pointer arithmetic。 「Total:」在記憶中表示爲'T''o''t''a''l'':'''0,所以「Total:」+ 4是'l'':'' '0.

2
cout << "Total: " << acc << endl; 
cout << "Max: " << max << endl; 
cout << "Min: " << min << endl; 
0

更改輸出線:

cout << "Total: " << acc << endl; 

使用< <操盤手+中。

相關問題