我正在尝试让该程序从用户处获取三个不同长度的值,就像W3Schools.com所说的那样,我将variablename.length();
放入代码中以获取用户输入的整行,但仅为其中之一工作。
我有3个(如果不是更多的话),为什么它只能工作这么多次,所以#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;
}