gpt4 book ai didi

c++ - 初级 C++ 输入行为

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:52 26 4
gpt4 key购买 nike

这个程序是我学习C++实践中的一个非常简单的代码。问题是在某些时候它不接受来自 cin 的输入并且行为异常。程序的代码和输出如下。

为什么程序在“请输入您的名字”时不考虑 cin

enter image description here

# include "cmath"
# include <iostream>
using namespace std;

int main()
{
string FirstName, MiddleName, LastName;
string WelcomeMessage = "Welcome to Visual C++";
int Number_of_Steps = 5;
int LoopStart = 1, LoopEnd = 5;
int AgeYears, AgeMonths;
double Pi = 3.14;
float k = 5.366;
double Age;
char* Symbol = "k";
bool TestResult = true;

MiddleName = "Milton";

cout << "Input Your First Name and Last Name" << endl;
cin >> FirstName >> LastName;
cout << "Input your Age in Years" << endl;
cin >> AgeYears;
cout << "Imput your Age in Months " << endl;
cin >> AgeMonths;
Age = AgeYears + AgeMonths / 12;
cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
cout << "Your Age is " << Age << endl;
cout << "The Character is " << Symbol << endl;

// Testing operators
cout << "Please Enter a floating point number \n";
int n;
cin >> n;
cout << "n==" << n
<< "\n n+1==" << n + 1
<< "\n n three times==" << 3 * n
<< "\n n twice ==" << n + n
<< "\n nsquared ==" << n*n
<< "\n half of n ==" << n / 2
<< "\n square root of n ==" << sqrt(n)
<< "\n";

// Testing string addition
cout << "Eneter your first name please" << endl;
string String1, String2, String3;
cin >> String1;
cout << "Enter your family name please" << endl;
cin >> String2;
String3 = String1 + " " + String2;
cout << "Welcome" << " " << String3 << endl;

// testing inequalities to strings
string FirstString, SecondString;
cout << "Input First String "
<< endl;
cin >> FirstString;
cout << "Input Second String "
<< endl;
cin >> SecondString;
if (FirstString == SecondString)
cout << "The two words are identical \n";
if (FirstString >= SecondString)
cout << "First word is bigger than second word \n";
if (FirstString <= SecondString)
cout << "Second word is bigger than first word \n";
}

最佳答案

您从显示 .2 作为名字 (String1) 的输出中得到提示。在询问名字之前的 cin 操作在缓冲区上有 64.2 但因为您将该值读入 int n 它只读取整数部分64 并将 .2 留在缓冲区中。将声明 n 更改为 float n 或在您确实需要整数时进行一些输入验证应该在您收到名字请求时将缓冲区留空。

关于c++ - 初级 C++ 输入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com