所以我试图让用户输入他们的名字和身高.
我有其他代码.
我有这个.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int name1;
cout << "What's your name?";
cin >> name1;
int height1;
cout << "What's your height?";
cin >> height1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是它不允许用户输入他们的身高.有任何想法吗?
问题是,你使用的是int变量而不是std :: string.但是,您已经包含了<string>头文件,因此您可能希望这样做:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
std::string name1;
cout << "What's your name?";
cin >> name1;
std::string height1;
cout << "What's your height?";
cin >> height1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
否则它只有在输入整数时才有效 - 但对于'名称'输入没有多大意义.
编辑:如果您还需要输入带空格的名称,则可以使用std :: getline
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
std::string name1;
cout << "What's your name?";
getline(cin, name1);
std::string height1;
cout << "What's your height?";
getline(cin, height1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |