2016-03-14 135 views
-2

我試圖創建一個程序,提示用戶輸入字符串以創建一個非常簡單的動畫。我的代碼工作正常,但是,當我試圖顯示字符串,我不能完全得到它的工作(第二個功能)請幫助!如何遍歷整個字符串並一次顯示一個字符C++

#include <iostream> 
#include <string> 
#include <cmath> 

using namespace std; 


void getAnimation(string& animation); 
void displayAnimation(string& animation); 

int main() 
{ 
    string animation; 

    getAnimation(animation); 

    displayAnimation(animation); 

    return 0; 
} 


//Ask user to enter a single frame 
//returned as string 
//Input Parameters: Numeber of Frames, Number of Lines, and Animation 
//Returns: The animation (string) 
void getAnimation(string& animation) 
{ 
    int counter, lines, i, numLines, frameNum; 

    cout << "How many frames of animation would you like?" << endl; 
    cin >> numLines; 

    // numbers to help with for - loop 
    counter = 0; 
    frameNum = 1; 

    //for - loop to get information 
    for (counter = 0; counter < numLines; counter++) 
    { 
    cout << "How many lines do you want in this frame?" << endl; 
    cin >> lines; 

    for (i = 0; i < lines; ++i) 
    { 
     cout << "Give me line of frame #" << frameNum++ << endl; 
     cin >> animation; 
     //getline(cin, animation); 
     //cin.ignore(); 
    } 
    } 
} 

//Will gather the string received in main and gather it here to display 
//Returned full animation 
//Input Parameters: None 
//Output Parameters: Animation 
void displayAnimation(string& animation) 
{ 
    cout << "Here is your super-sweet animation!\n"; 

    // to print out entire animation 

    //for (auto c : animation) 
    //cout << animation << endl; 
    //for (int i = 0; i < animation.length(); i++); 
} 
+0

什麼確切的問題正在面臨着? –

+0

該程序只輸出我輸入的最後一個字符,而不是整個字符串。 –

+0

在'getAnimation'內的'animation'中放置的最後一個值是返回到'main()'的那個值,然後在那裏將其傳遞給'displayAnimation'。如果這不是你的意圖,請更改代碼。 – WhozCraig

回答

1

animationstring不是數組左右因此for (auto c : animation)不會工作。要獲得單個字符,只需執行animation.at(i)其中i是所需字符的索引。您也可以使用stringstream

char c; 
std::istringstream iss(animation) 

while (iss.get(c)) 
{ 
    // Do animation here 
} 

並且不要忘記包括sstream


此外,您的代碼還有另一個問題。您期望animation可以保持輸入的多行輸入,對吧?由於aninamtionstd::string而非數組或vector,正如我在提到它之前所提到的那樣,它使用cin >> animation來表示它的鑽孔時間。您應該使用std::vector<string>作爲您的方法。

於是宣佈動畫像這樣std::vector<string> animationgetAnimation你這時就需要做這樣的事情:

for (i = 0; i < lines; ++i) 
{ 
    cout << "Give me line of frame #" << frameNum++ << endl; 
    string tmp; 
    cin >> tmp; 
    animation.push_back(tmp); 
} 

displayAnimation你應該在vector,然後第一循環在它存儲得到的strings單個字符。

for (size_t i = 0; i < animation.size(); ++i) 
{ 
    istringstream iss(animation.at(i)); 
    char c; 
    while (iss.get(c)) 
    { 
    cout << c; 
    } 
} 

您還需要在函數聲明更改爲void getAnimation(vector<string>& animation)和'無效displayAnimation(矢量&動畫)

相關問題