0

I have a simple program as follows:

#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; } 

My output is getting chopped off as follows

./stat Enter N: 3 1 2 3 : in: 

What am I doing wrong?

3 Answers 3

4

In C++, the operator + on a string and a number behaves differently than you might expect from higher level languages.

"Total: " for instance is a character array, and if a[10] is your array, a + 5 is the slice of the array starting at a[5]. This is known as pointer arithmetic.

"Total: " is represented in memory as 'T' 'o' 't' 'a' 'l' ':' ' ' 0, so "Total : " + 4 is 'l' ':' ' ' 0.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Change your output lines to:

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

Use the << operator instead of +.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.