首页 > 解决方案 > 存储和打印字符,但输出不是预期的

问题描述

我对 C++ 很陌生。这段代码应该存储并打印出每隔一个数字并在给定符号时停止#,但输出很奇怪。它输出类似0x6fdd90. 任何帮助将非常感激。

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

int main(){
    string s[11];
    int count = 1, wordlength = 0;
    char a;

    cin.get(a);

    while (a != '#'){
        if (wordlength == 10)
            break;
        if (count % 2 != 0){
            s[wordlength] = a;
            wordlength++;
        }
        cin.get(a);
        count++;
    }
    s[wordlength] = '\0';
    cout << s;
    return 0;
}

标签: c++

解决方案


 cout << s;

正在打印数组中第一个元素的地址s。您可能需要循环s打印所有元素。

for (int i =0; i < sizeof(s)/sizeof(s[0]); i++) {
    cout<< s[i] << "\n";
}

出于您的目的,使用 char 数组比使用字符串数组更好。


推荐阅读