2013-08-02 27 views
1

我已經在C++一個簡單的程序,這是代碼:如何讓用戶鍵入一個值而不是存儲常量值?

#include <iostream> 
using namespace std; 

int main() 
{ 
    int number; 
    int square; 

    number = 5; 
    square = number * number; 
    cout << "The square is "; 
    cout << square; 

    return 0; 
} 

它做什麼基本上是取整數「5」,畫面上出現的平方值等等...

我的問題是:

我該如何讓程序從用戶處取任何值而不是將值存儲在內存中?

比Q

+5

你應該繼續閱讀你的書。 – Rapptz

回答

4

你的代碼使用的cout打印。 C++使得可以從控制檯輸入cin

int x; 
cin >> x; 
+0

謝謝。現在我知道cout和它的對面cin的含義 – user2624929

3

「一個例子是勝過千言萬語......」

cout需要一些變種。從內存中將其打印出來,對嗎?
好,cin做的正好相反,它需要從鍵盤輸入一些值,並把它在你的記憶..

你必須採取在價值與cin命令的幫助,像這樣:

int a; //lets say you have a variable 
cout << "Enter a value here: "; //prompts the user to enter some number 
cin >> a; //this line will allow the user to enter some value with the keyboard into this var. 
int square = a * a; 
cout << "The square is: " << square; 

希望它可以幫助...

+0

真的有幫助。謝謝,,, – user2624929

+0

@ user2624929在欣賞的答案接受他們的最好辦法,兄弟:) – tenstar

2

只需更換:

number = 5; 

用:

cout << "What's the number? "; 
cin >> number; 

你已經知道如何使用cout生成輸出,這只是使用cin檢索輸入。請記住,儘管對於小型測試程序或學習來說這可能沒問題,但真正程序中的數據輸入通常會更穩健一些(例如,如果您在輸入字符串xyzzy時嘗試輸入變量int變量)。

+0

謝謝你,但說它建立一個更大程序時變得更加複雜,否則會有比其他CIN另一個編碼技術和cout – user2624929

+0

@ user2624929,我說如果你輸入'xyzzy',結果將不會是你期望從一個強大的程序中得到的結果。一個健壯的程序會輸出一個錯誤,比如'「那不是數字,你就是鵝!」然後再問一次,而不是繼續使用狡猾的數據。你仍然可以使用cin,但是你會做額外的檢查。 – paxdiablo

相關問題