C ++:从向量中读取元素,跳过循环

时间:2013-05-04 18:27:22

标签: c++ loops vector skip

目前正在尝试编写一个程序,要求用户输入字符串,然后通过迭代器读取这些值。该程序的最后一步是在将消息显示给用户之前对消息应用简单的凯撒转换。但是,因为我似乎犯了一个错误导致程序跳过“for”循环(或者我使用的循环,我尝试了从“for”到“while”到“if,else”循环的所有内容)。我对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;
}

我花了相当多的时间研究类似的情况,但据我所知,我已经错过了其他人在类似情况下陷入的陷阱。当然,作为新人,我总是错的,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分: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>位于顶部,以便工作。