-2

I am making a program to decode a given message by using a specified key! I m trying to come up with a my own way and it requires me to create several arrays! To check if the input was being displayed correctly(or stored properly) i m trying to display it but it somehow comes incorrect always when i have all the arrays declared when i declare only the one which i want to see ,for example only mes then it works perfectly fine! Is this some kind of overflow situation? should i use dynamic allocation?

int main() {


   int t;
   cin>>t;
   char key[7],d[26],k[7],o[255],mes[255];
   while(t--){     //loop doesn't

    cin>>key;
    cout<<key<<endl;
    cin.getline(mes,255);
    cout<<mes;
    //rest of the code 
   }
     return 0;
}

**

for input: 1
     key
     mess mess mess mess 
output expectation is 
     key 
     mess mess mess mess
but actual outcome is
     key
     mess
       mess mess mess

**

also the loop does not work!

Dhruva-404
  • 168
  • 2
  • 10

1 Answers1

0

As described in the duplicate you can use std::istream::ignore. std::istream::operator>> only reads the non-whitespace characters. After

cin>>key;

the newline character stays in the buffer. With

cin.getline(mes,255);

you read only this one newline character. With std::istream::ignore you can ignore it:

#include <iostream>
#include <sstream>

int main() {
  std::stringstream input("1\nkey\nmess mess mess mess\n");
  std::cin.rdbuf(input.rdbuf());
  int t;
  std::cin >> t;
  char key[7], d[26], k[7], o[255], mes[255];
  while(t--) {
    std::cin >> key;
    std::cout << key << std::endl;
    std::cin.ignore();
    std::cin.getline(mes, 255);
    std::cout << mes;
  }
  return 0;
}

But I recommend to use std::string instead of c strings.

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::stringstream input("1\nkey\nmess mess mess mess\n");
  std::cin.rdbuf(input.rdbuf());
  int t;
  std::cin >> t;
  std::string key, d, k, o, mes;
  while(t--) {
    std::cin >> key;
    std::cout << key << std::endl;
    std::cin.ignore();
    std::getline(std::cin, mes);
    std::cout << mes;
  }
  return 0;
}

Output in both examples is

key
mess mess mess mess
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62