我正在尝试让该程序从用户处获取三个不同长度的值,就像W3Schools.com所说的那样,我将variablename.length();
放入代码中以获取用户输入的整个行,但仅适用于其中一个。
我有三个(如果不是更多的话),为什么它只能工作这么多次,所以#include files
中缺少某些东西或其他东西。该代码非常简单,我以为我试图对其进行遍历并使其尽可能详细。这是代码:
// CreateWriteDisplay.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <cstring>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
void OpeningMessage() {
cout << "Enter Your First Name and Last name:";
cout << "Enter Your Age: ";
cout << "Enter Your Ocupation:";
cout << " This is yout Ocupation:";
}
int main()
{
OpeningMessage(), "\n";
int AccountAge;
string FullName;
string Ocupation;
cin >> AccountAge;
cin >> FullName;
cin >> Ocupation;
cout << FullName << FullName.length() << "\n";
cout << AccountAge << "\n";
cout << Ocupation << Ocupation.length();
return 0;
另外,如果有人知道了W3Schools网站之类的教程,那么如果您不能说我是C++编程的初学者,那么我真的可以使用该实践。我在第一个教程上做的测试真的很好。我真的很喜欢这种语言,它使我想起了一些JavaScript,但功能却强大得多。因此,任何帮助将不胜感激。先感谢您。
最佳答案
我猜你的问题是
cin >> FullName;
将在第一个空格处停止读取,因此,如果输入名字和姓氏,则将读取名字,并且姓氏将保留在缓冲区中。
然后将由下一个
cin
读取cin >> Ocupation;
您可以通过将名字和姓氏分成两个单独的变量或使用
std::getline
来解决此问题。如您刚开始时,最好使用第一个解决方案,然后再访问
getline
。我建议:#include <iostream>
using std::cout; //using namespace std is not a good practice **
using std::cin; //it's best to use std:: scope or using only what you need
using std::string; //not the whole namespace, C++17 allows for comma
using std::endl; //separated usings
int main()
{
int AccountAge;
string LastName;
string FirstName;
string Ocupation;
cout << "Enter Your Age: ";
cin >> AccountAge;
cout << "Enter Your First Name and Last name: ";
cin >> FirstName >> LastName;
cout << "Enter Your Ocupation: ";
cin >> Ocupation;
cout << "Full Name: " << FirstName << " " << LastName << ", Length: " <<
FirstName.length() + LastName.length() << endl;
cout << "Age: "<< AccountAge << endl;
cout << "Occupation: " << Ocupation << ", Length: " << Ocupation.length();
return 0;
}
** Why is "using namespace std;" considered bad practice?
关于c++ - 接受用户输入并显示它的程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61327019/