[英]In C++ while using cin.get(), how can I not limit the number of characters a user can enter?
我试图使用cin.get()获取用户输入,但我不想限制他们可以输入的字符数量。 我怎样才能做到这一点?
编辑:我想用一种更好的方式来表达这一点是:我如何动态地更改字符数组以适合用户输入的长度?
对于C ++程序,这是一个奇怪的要求。 当然,您可以采用C方式,只要输入超出当前可用的内存就可以继续获取更多的内存。 它是这样的( 警告:前面的代码片段 ):
while(cin.get(c)) {
if (cur_pos == cur_len) {
cur_len = grow_charbuf(buffer, cur_len);
}
buffer[cur_pos++] = c;
}
在这里, grow
功能变得很难看。 它需要分配更大的内存,将当前缓冲区的内容复制到该缓冲区的开头,重新分配当前缓冲区所占用的内存,并返回新的大小。 例如,遵循以下原则:
char* new_charbuf(size_t len) {
return new char [len];
}
size_t grow_charbuf(char* buf, size_t cur_len) {
size_t new_len = cur_len * 2;
char* new_buf = new char [new_len];
// copy old buffer contents to new buffer
delete[] buf;
buf = new_buf;
return new_len;
}
然后您可以按以下方式使用它:
cur_len = 1000; // or whatever
char* buffer = new_charbur(cur_len);
// write into the buffer, calling grow_charbuf() when necessary
// and don't forget to free the memory once you are done...
// or don't free it, if the program eventually exits anyway
这是可怕的代码。 它可能会起作用,但是如果可以避免,则永远不要在C ++中这样做。 除此之外,我避免处理此代码可能引起的任何错误情况或异常。 这只是为了说明这个想法。
手动管理内存不是一个好主意,因为它需要大量代码,而且不容易正确使用。 如果您的程序的寿命已知有限,那么您可以少花钱。
根本不使用字符数组。 使用std :: string或其他标准容器。 当然要学习使用流。
这里举个例子。 它读取的字符数与用户输入的字符数相同,直到用户按下Enter键为止。 正如您所看到的,不需要显式的缓冲区大小:
/////TEST PUT ANYWHERE IN GLOBAL SCOPE
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int test()
{
//SET BP HERE AND STEP THROUGH
string line;
getline(cin,line);
std::stringstream user_input( line );
while(!user_input.eof())
{
string word;
user_input >> word;
cout << word << endl;
}
return 0;
}
static int _test = test();
/////END TEST
您需要一个cin.getline()。 换句话说,您需要具有指定大小的char数组并按如下方式使用它:
使用cin.get()
char str[100];
char sayHello[100];
cin.get(str, 100);
// make sure to add cin.ignore() or program will terminate right before next cin().
cin.ignore();
cout << str << endl;
cin.get(sayHello, 100);
cout << sayHello;
或cin.getline()
char input[100];
cin.ignore(); // stops the sentence from truncating.
cin.getline(input,sizeof(input));
您还可以将getline()用于类似这样的字符串:
string name;
getline(cin, name);
问题是在c ++中,当接收到输入时,您的cin查找句子中空格(也就是0)。 然后以为结束就结束了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.