2013-05-04 47 views
0

當前正試圖編寫一個程序,它會詢問用戶輸入的字符串,然後通過迭代器讀取這些值。該程序的最後一步是在顯示給用戶之前,將簡單的凱撒轉換應用到消息中。然而,因爲我似乎犯了一個錯誤,導致程序跳過「for」循環(或者我使用的任何循環,我嘗試了從「for」到「while」到「if,else」循環的所有內容)。我對C++相對來說比較新,所以我希望儘管我盡了最大的努力,但仍然錯誤地設置了我的循環。C++:從矢量中讀取元素,循環被跳過

#include <iostream> 
#include <vector> 
#include <string> 

int main() { 
    std::vector <std::string> vector_1; 
    int c; 
    int d = 0; 
    int i = 0; 
    std::string message; 
    std::vector<std::string>::iterator it_1; 

    std::cout << "Please input the message to be Caesar Shifted \n"; 

    while (std::cin >> message, d != 0) { 
     vector_1.push_back (message); 
     ++d; 
    } 

    std::cout << "Encrypted message is"; 

    for (std::vector<std::string>::iterator it_1 = vector_1.begin(); it_1 != vector_1.end(); ++it_1) { 

    std::cout << *it_1; 
    } 

return 0; 
} 

我花了很多時間相當數量的研究類似的情況,但據我所知,我已經錯過了陷阱其他人在類似情況下陷入。當然,新的,我總是可能會錯,所以任何幫助將非常感激。

+0

d = 0; (std :: cin >> message,d!= 0)總是會出錯(並且不會進入while循環)。你想用d做什麼? – selalerer 2013-05-04 18:33:06

+0

意圖是設置一個觸發器,while循環會在按下「enter」鍵時結束,雖然在擺弄nullptr的回答後,我發現問題出在第一個循環而不是第二個循環。 – 2013-05-04 18:37:16

回答

0
it_1 < vector_1.end() 

應該

it_1 != vector_1.end() 

while (std::cin >> message, d != 0) { 
    vector_1.push_back (message); 
    ++d; 
} 

應該

getline(std::cin, message); 
std::stringstream ss(message); 
std::string temp; 
while (ss >> temp) 
    vector_1.push_back(temp); 

你會在上面這個工作要#include <sstream>

+0

最初的意圖是讓程序在按下回車鍵時停止輸入,儘管概念是相同的。 – 2013-05-04 18:41:43

+0

@ScottHowland我更新了我的答案 – nullptr 2013-05-04 18:46:44

+0

非常感謝,nullptr。我很抱歉如果我的問題含糊不清,還是習慣了這個網站。不過,我很高興能夠在排列這些混亂的過程中學習一些關於串流的知識。 – 2013-05-04 18:56:28