c++ - 为什么只打印名字的第一个字母?
问题描述
#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;
}
跑步是什么样子的:
解决方案
使用字符串而不是字符。一个字符只获取输入的第一个字母。代码应如下所示。
#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;
}
推荐阅读
- css - 如何移动(中心)一个 svg 图标?
- r - 在 R 中绘制均值/平均 ROC 曲线的简单方法
- c# - 整数不应该减少吗?
- reactjs - 使用打字稿,我如何使用reduxForm,connect和withRouter一起使用
- regex - 如何排除部分正则表达式匹配?
- c# - 为什么我在 TextChanged 事件中运行相同的代码而不是 Button Click 时会得到不同的结果?
- reactjs - 无法在 Storybook 中按类名设置我的 React 组件样式
- marklogic - 使用 ml-gradle 对 REST API 选项的权限
- c - 读取访问中断:树为 0xAE0A74BF
- node.js - 浏览 Docker 托管的应用程序时出现 ERR_CONNECTION_REFUSED