2013-05-04 50 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