接受用户输入并显示它的程序 问题

Program to take in user input & display it Problems

我试图让这个程序以不同的长度从用户那里获取三个值,所以就像 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;

将在第一个空格 space 处停止读取,因此如果您输入名字和姓氏,将读取名字,而姓氏将保留在缓冲区中。 它将被下一个 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?