为什么这个程序不表现 LIke 一个无限的输入行 - c++

Why Is This Program Not Behaving LIke An Unlimited Input Line - c++?

本文关键字:无限 输入 一个 c++ 程序 为什么 LIke      更新时间:2023-10-16

我试图创建一个C++程序,允许用户输入他/她喜欢的字符数量(只要内存可以接受(,一旦他们按回车键(ASCII编号:13(,程序就会打印出用户输入的整个字符串。

但是由于某种原因,即使程序需要您输入的尽可能多的字符,它也不会打印出用户输入的整个字符串......好吧,它只是停止运行,当我查看我的 Windows 资源监视器时,它显示该程序发生了内存泄漏,几秒钟内就会清理干净,但我真的很想知道我的程序出了什么问题。

提前致谢

这是我的整个源代码:

    #include<iostream.h>
    #include<conio.h>
     int main()
     {
       int ctr = 0, n = 10, counter = 0;
       char *stloc = NULL, *ptr = NULL, *cptr = NULL; // creating a NULL pointer
       ptr = new char[n]; // get an array of 10 bytes allocated in heap memory
       while((int)(*ptr) != 13) // Take input till Enter Key is pressed
       {
        if(counter == (n+ctr-1)) // Check if array overflow is going to happen
        {
               ctr+=2; // add two to ctr so that an extra 2 byte space is created in the new char array for a character and ''
               cptr = new char[n+ctr];
               strcpy(cptr,ptr);
               delete [] ptr;
               ptr = cptr;
               stloc = ptr;
        }
        *ptr = getche();
        ptr++;   
        counter++;
      }    
      *ptr = '';
      cout << endl << stloc;
      delete [] ptr;
      system("pause");
    }

您可以使用std::stringstd::getline来阅读整行文本。(这将在第一个换行符处。能够做到这一点的简单程序是:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string myLine;
  getline(cin, myLine);
  cout<<myLine<<endl;
}

如需进一步阅读,您可以查看 std::string 和 std::getline 的文档。