为什么这个程序不表现 LIke 一个无限的输入行 - c++
Why Is This Program Not Behaving LIke An Unlimited Input Line - c++?
我试图创建一个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::string
和std::getline
来阅读整行文本。(这将在第一个换行符处。能够做到这一点的简单程序是:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myLine;
getline(cin, myLine);
cout<<myLine<<endl;
}
如需进一步阅读,您可以查看 std::string 和 std::getline 的文档。
相关文章:
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 陷入输入C++的无限循环中
- 字母输入运行无限循环
- 为什么输入流无法识别 Ctrl D 并给出无限循环
- 如何在用空格分隔的行中获得无限的输入
- 开关大小写语句中函数中的字符串输入会导致无限循环和绕过输入
- 为什么这个程序不表现 LIke 一个无限的输入行 - c++
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 为什么当用户输入除整数之外的任何内容时,我的程序会无限循环输出?C++
- 循环时的输入验证是无限的
- 输入 2 个非常基本的 C 字符串时的无限循环
- 无限输入C 计算器要结束计算,需要再进行一个INT
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 如何在 c++ 中从".in"格式的文件中获取输入?此代码进入无限循环,但适用于".txt"文件格式
- 为什么我的程序在输入字符时有一个无限循环
- 输入验证,需要数字,而不是字符串.代码导致无限循环
- 在等待输入时执行无限循环
- 如何允许无限数量的名称输入
- 我使用什么类型的代码来允许无限输入