c++ - 为什么我的字符串无法在 C++ 中正确打印?

标签 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:

我做错了什么?

最佳答案

在 C++ 中,运算符 +在字符串和数字上的行为与您对高级语言的预期不同。

“总计:”例如是一个字符数组,如果a[10]是你的数组,a + 5是从 a[5] 开始的数组切片.这被称为 pointer arithmetic .

"Total: "在内存中表示为 'T' 'o' 't' 'a' 'l' ':' ' ' 0,所以 "Total : "+ 4 是 'l' ':' ' ' 0.

关于c++ - 为什么我的字符串无法在 C++ 中正确打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16507414/

相关文章:

c++ - 使用 Pimpl 模式的模拟类

c++ - "Missing non-virtual thunks"和继承顺序

c++ - 在 beaglebone black 上使用 arm-linux-gnueabihf 时跳过不兼容错误

c++ - printf 数据类型说明符复杂问题

c++ - 默认复制构造函数和复制赋值赋值运算符给出奇怪的错误

c++ - 从数组更改为包含数组的结构

c++ - 我可以用模板处理迭代器吗?

c++ - 在 Armadillo 中捕获 LAPACK 错误

c++ - 不打印 5 个字母长的 unicode

c++ - 缩小从 char 到 uint8_t 的转换