Question

Currently trying to write a program which will ask the user for their input for a string, then read off these values via an iterator. The final step for this program would be to apply a simple caesar shift to the message before displaying it back to the user. However, since I appear to have made an error which causes the program to skip over the "for" loop (or whichever loop I use, I have tried everything from "for" to "while" to "if, else" loops). I'm relatively new to C++, so I'm hoping I simply set up my loop incorrectly, despite my best efforts.

#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;
}

I spent a fair amount of time researching similar situations, but as far as I can tell, I've missed pitfalls others have fallen into in similar situations. Of course, being new, I could always be wrong, and so any help would be very much appreciated.

Was it helpful?

Solution

it_1 < vector_1.end ()

should be

it_1 != vector_1.end ()

and

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

should be

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

You'll want to #include <sstream> at the top for this to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top