考虑你的任务的限制(没有std::string
,没有std::vector
,动态内存分配) ,我会尝试给你一个修改过的但是你的代码的工作版本。
我的想法是读取字符串字我的话,并停止时,它到达EOF或 \ n。你能指出这个错误吗?
由于molbdnilo指出(c!=EOF) || (c!='\n')
总是如此,所以你的循环将永远不会结束。
由于mah注意到,您的缓冲区只有1个字符长度,并且您不检查溢出,此外,您忘记在其末尾添加空白定界符。
你的第二个问题是关于当new
不能分配足够的内存时会发生什么。那么,它会抛出一个你的程序应该处理的异常,但最好的事情(不是唯一的一个,也许是最简单的)你可以做的就是终止你的程序。
这是考虑到上述限制如何完成你的任务的例子:
#include <iostream>
using namespace std;
const int INITIAL_SIZE = 8;
int main() {
// the following block of code could rise an exception
try
{
int n = 0;
char c;
// allocate some memory to store the null terminated array of chars
char *a = new char[INITIAL_SIZE];
// what happens if new fails? It throws an exception of type std::bad_alloc
// so you better catch it
int allocated = INITIAL_SIZE;
// read a charachter from stdin. If EOF exit loop
while(cin.get(c))
{
// If it's a newline or a carriage return stop
if('\n' == c || '\r' == c)
//^ note that ^^^ putting the literals first helps avoiding common
// error like using "=" instead of "==" in conditions
break;
a[n] = c;
// if the array is full it's time to reallocate it
if (n == allocated)
{
// There are alternatives, of course, but I don't know which library
// you are allowed to use, so I assume no one and BTW your compiler
// could be smart enough to recognize the pattern and optimize it
// allocate a bigger array
allocated *= 2;
char *b = new char[allocated];
// copy the old one in the new one
for (int i = 0; i <= n; ++i)
{
b[i] = a[i];
}
// release the memory handled by the old one...
delete[] a;
// but keep using the same pointer. Just remember not to delete b
// so that a allways points to allocated memory.
a = b;
}
// a new character has been succesfuly added
++n;
}
// now before using a, we have to add the null terminator
a[n] = '\0';
// note that a doesn't contain the '\n'
cout << a << '\n';
delete[] a;
// normal program termination
return 0;
}
// If new fails to allocate memory a std::bad_alloc exception is thrown
catch (const exception &e)
{
cout << "Exception caught: " << e.what() << "\nProgram terminated.\n";
return -1;
}
}
在C++中,使用String类此。 – Donnie
C++中的自然方法是使用'std :: string'和'getline'或'>>'来读入字符串。否则,你需要保持重新分配和复制到一个更大的数组。 – crashmstr
您是否特别试图不使用标准库工具'std :: string'和'getline'? –