2
這個程序是我學習C++的一個非常簡單的代碼。問題是在某些時候它不接受來自cin
的輸入並且表現奇怪。 該程序的代碼和輸出如下。初學C++輸入法beiviviour
爲什麼程序在「請輸入你的名字」時不考慮cin
?
# 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";
}
感謝Logan的幫助 - 但請您進一步解釋一下嗎? –
當你說'int n; cin >> n;'和'cin'包含'3.14',它只會從'cin'中讀取整數'3',並將'.14'保留在'cin'中。當你到達'cin >> String1;'它不會要求用戶輸入任何東西,因爲'cin'已經包含'string':'.14'可以被認爲是一個字符串。所以它將'.14'寫入'String1'並繼續。 –
將'n'改成'float'會修正它。在請求輸入之前擦除'cin'的內容也解決了這個問題 - [這是怎麼回事](http://stackoverflow.com/a/257182/2449857)。對不起,這不是一個非常優雅的方式 –