How to read more than one line of input?

Viewed 134

So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.

ps: I use CodeBlocks

#include <iostream>
#include <ctype.h>

using namespace std;

int main()
{
    std::string str;
    char enc;
    int word;
    cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
    cout << "\t\t\t\t\t\t\t\t---------" <<endl;
    cout << "Enter a Word: ";
    getline(cin, str);
    int n = 0;
    cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D@T@" <<endl;
    cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
    for(int i = 0; i < str.length(); i++){
        int randomAdd[5] = {5,6,2,3,2};
        int size = sizeof(randomAdd)/sizeof(randomAdd[0]);
//        for(int j = 0; j < 5; j++){
        word = str.at(i);
        if(i%5 == 0){
            n = 0;
        }
        enc = int(word) + randomAdd[n];
        std::cout << char(enc);
        n++;
    }

 return 0;
}

This works

Hello World

But I cannot enter this

Hello World
Have a nice day

because then the program exits command prompt without any error or message.

How can I read more than one line?

2 Answers

This code sample allows you to input multiple lines interactively from the command line/shell

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

using namespace std;

int main()
{
    string str;
    char enc;
    int word;
    vector<string> myInput;
    cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
    cout << "\t\t\t\t\t\t\t\t---------" <<endl;
    while (str != "Enigma")
    {
        cout << "Enter a line (Write Enigma to exit input): ";
        getline(cin, str);
        myInput.push_back(str);
    }
    int n = 0;
    cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D@T@" <<endl;
    cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
    for(auto & myInputLine : myInput)
    {
        str = myInputLine;
        for (size_t i = 0; i < str.length(); i++) {
            int randomAdd[5] = { 5,6,2,3,2 };
            int size = sizeof(randomAdd) / sizeof(randomAdd[0]);
            word = str.at(i);
            if (i % 5 == 0) {
                n = 0;
            }
            enc = int(word) + randomAdd[n];
            std::cout << char(enc);
            n++;
        }
    }
    return 0;
}

The input is finished if Enigma is written.

All input is stored in the vector container of the STL, see vector.

Afterwards, all the lines are encrypted by your algorithm.

Hope it helps?

You can do as

#include <iostream>

using namespace std;

int main() {

  string str;
  
  while (getline(cin, str)) {
    cout << str << endl;
  }

  return 0;
}
Related