首页 > 解决方案 > 为什么只打印名字的第一个字母?

问题描述

#include<iostream>
using namespace std;

int main()
{

    int age;
    char name;
    cout<<"Enter age and name: ";
    cin >> age >> name;
    cout <<endl <<"your age: "<< age << endl << "name is: "<< name;


    return 0;
}

跑步是什么样子的:

图片

标签: c++visual-c++cin

解决方案


使用字符串而不是字符。一个字符只获取输入的第一个字母。代码应如下所示。

#include<iostream>

using namespace std;

int main() {
    int age = 0;
    string name = "";
    
    cout<<"Enter your age and name: ";
    
    cin >> age >> name;
    
    cout << endl;
    
    cout << "Your age is " << age << endl;
    cout << "Your name is " << name << endl;
    
    return 0;
}

如果需要使用字符,可以尝试使用向量。

#include <iostream>
#include <vector>

using namespace std;

vector<char> _myStr;

void DisplayList () {
    cout << "Your name is: ";

    for (int i = 0; i < _myStr.size(); i++) {
        cout << _myStr[i];
    }

    cout << endl;
}

void ConvertToVector (string theStr) {
    for (int i = 0; i < theStr.length(); i++) {
        _myStr.push_back(theStr[i]);
    }
}

int main () {
    int age = 0;
    string name = "";

    cout << "Enter your age and name: ";
    cin >> age >> name;

    cout << endl;

    ConvertToVector (name);   

    cout << "Your age is: " << age;
    DisplayList ();

    return 0;
}

推荐阅读