2012-10-12 13 views
0

我幾乎完成了代碼,我只需要弄清楚如何使用cout和cin來製作角色的用戶輸入值和三角形的高度,謝謝這是我所有的代碼硬編碼。我需要讓用戶輸入一個三角形和一個字符的值嗎?

我覺得我說錯了基本上,該程序應該繪製一個三角形使用函數drawline我創建下面,當我編譯和運行它要求我輸入用戶選擇,如果我輸入1它運行代碼在if(userChoice == 1){}基本上我想要一個cin和cout代碼結構,允許它們爲lineLength和displayChar輸入它們的值。

#include <iostream> 
#include <string> 
#include <math.h> 

using namespace std; 

void drawLine (int lineLength, char displayChar); 
void placePoint (int lineLength) ; 

int main() 
{ 
    int userChoice = 0; 
    cout << "**********************************" << endl; 
    cout << "* 1 - DrawTriangle *" << endl; 
    cout << "* 2 - Plot Sine graph *" << endl; 
    cout << "* 3 - Exit *" << endl; 
    cout << "Enter a selection, please: " << endl; 
    cin >> userChoice; 

    int x,y,t =0; 
    char displayChar = ' '; 
    int lineLength = 0; 
    double sinVal= 0.00; 
    double rad = 0.00; 
    int plotPoint = 0; 

    if (userChoice == 1) 
     for (int x=1; x <= lineLength; x=x+1) { 
      drawLine (x, displayChar); 
     }//end for 

    for (int y=lineLength-1; y >= 1; y=y-1) { 
     drawLine (y, displayChar); 
    }//end for 
}//end main at this point. 

void drawLine (int lineLength, char displayChar) 
{ 
    for (int x=1; x <= lineLength; x=x+1) { 
     cout << displayChar; 
    } 
    cout << endl; 

    for (int y=y-1; y >= 1; y=y-1) { 
     cout << displayChar; 
    } 
    cout << endl; 
} //end drawline 
+0

只需用'cout'向用戶詢問並用'cin'輸入? –

+0

謝謝我試圖直接使用變量lineLength和displayChar,如果你看到它的字符數量,它會給我你會笑你的頭,它只是不斷迭代 –

+0

這正是我所做的@JoachimPileborg cout << Enter三角形長度的值<< endl; cin >> lineLength; cout <<選擇要使用的字符:<< endl; cin >> displayChar; –

回答

0

的問題是,cin是一個流(見reference document),所以你不能只是流價值爲userChoice,因爲它是一個int。相反,你需要使用一個字符串:

string response; 
cin >> response; 

然後,你需要解析字符串得到INT,採用的方法之一this SO question,像strtol。在這裏閱讀整數

類似的問題:How to properly read and parse a string of integers from stdin C++

或者,只是使用字符串response您比較:

if(response == '1') { 
    //... 
} 
+0

非常感謝我知道我不是直接流到userChoice,而是試圖讓它在lineLength和displayChar變量中確定字符和高度 –

+0

違規行是'cin >> userChoice;' - userChoice已聲明作爲一個整數。 –

+0

請原諒我,如果我錯了 - 我認爲<<重載,它的工作原理基於變量的類型,我相信在這種情況下,cin將返回一個整數。 – Raj

-1

您不能使用cin設置一個整數。由於cin是一個流,您可以使用它來設置一個字符串。從那裏你可以使用atoi將字符串轉換爲整數。您可以在cplusplus.com上查看更多詳情。

你的實現應該是這樣的:

string userChoiceString; 
cin >> userChoiceString; 
userChoice = atoi(userChoiceString.c_str()); 
+0

我覺得我說它錯了基本上該程序應該繪製一個三角形使用函數drawline我創建下面,當我編譯和運行它要求我輸入用戶選擇,如果我輸入1它運行的代碼中的if(userChoice == 1){}基本上我想要一個cin和cout代碼結構,允許他們輸入lineLength和displayChar的值。 –

+0

感謝您編輯我的回覆,我仍然是新的堆棧溢出&我試圖得到這個網站和社區的工作方式:) – innospark

0
for (int y=y-1; y >= 1; y=y-1) 

初始化y以一個不確定的值。這意味着循環會有一個隨機的,可能很長的持續時間。

相關問題