是什么导致异常输出以及如何修复它

时间:2019-05-19 10:51:47

标签: c++

我正在制作一个程序,使用指定的密钥解码给定的消息!我试图提出自己的方式,这需要我创建多个阵列!要检查输入是否正确显示(或正确存储),我试图显示它,但是当我声明了所有要声明的数组时,总是以某种方式出现错误。正常工作!这是某种溢出情况吗?我应该使用动态分配吗?

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

**

循环也不起作用!

1 个答案:

答案 0 :(得分:0)

如重复所述,您可以使用std::istream::ignorestd::istream::operator>>仅读取非空白字符。

之后
if (data.isClosed != true) {
   map.setCenter(new google.maps.LatLng(data.latitudine, data.longitudine));
   map.setZoom(17);
} else {                    
   GetAllNeighboors(data.latitudine, data.longitudine, function(Neighboors){
       Vecini = new Object();
       Vecini = Neighboors
});

换行符保留在缓冲区中。与

cin>>key;

您仅读取此一个换行符。使用std::istream::ignore,您可以忽略它:

cin.getline(mes,255);

但是我建议使用std::string而不是c字符串。

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

两个示例的输出均为

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