【问题标题】:Why Is This Program Not Behaving LIke An Unlimited Input Line - c++?为什么这个程序的行为不像无限输入行 - c++?
【发布时间】:2017-03-20 13:13:50
【问题描述】:

我试图创建一个 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 '\0'
               cptr = new char[n+ctr];
               strcpy(cptr,ptr);
               delete [] ptr;
               ptr = cptr;
               stloc = ptr;
        }
        *ptr = getche();
        ptr++;   
        counter++;
      }    
      *ptr = '\0';
      cout << endl << stloc;
      delete [] ptr;
      system("pause");
    }

【问题讨论】:

  • 你从哪里得到用户的输入?另外为什么不使用std::string?您的整个程序可以替换为std::string input; std::getline(std::cin, input);
  • 由于您正在执行指针运算以使用ptr 作为迭代器,因此调用delete ptr 是一个非常糟糕的主意。而且由于它不是字符串的开头,因此调用strcpy(cptr, ptr) 来传输内存内容也是一个坏主意。即便如此,在每次调整大小并覆盖内容后,您仍将 ptr 重置为字符串的开头。
  • C 运行时库将 Return 转换为换行符 ('\n'),其 ASCII 码是 10 而不是 13...此时您测试 *ptr , ptr 指向一个未初始化的值!在第一次运行时,什么都没有读过,接下来,你只是增加了 ptr...除非你有特殊要求,否则停止使用 conio 并遵循 C++ 教程。

标签: c++ memory-management dynamic memory-leaks


【解决方案1】:

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

#include <iostream>
#include <string>

using namespace std;

int main() {
  string myLine;
  getline(cin, myLine);
  cout<<myLine<<endl;
}

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

【讨论】:

    猜你喜欢
    • 2013-09-28
    • 2017-11-08
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多