简体   繁体   English

在C ++中使用cin.get()时,如何不限制用户可以输入的字符数?

[英]In C++ while using cin.get(), how can I not limit the number of characters a user can enter?

Im trying to get a users input using cin.get() but I dont want to limit the amount of characters that they can enter. 我试图使用cin.get()获取用户输入,但我不想限制他们可以输入的字符数量。 How can I do this? 我怎样才能做到这一点?

EDIT: I guess a better way to phrase this would be: How can I dynamicaly change the character array to fit the length of the users input? 编辑:我想用一种更好的方式来表达这一点是:我如何动态地更改字符数组以适合用户输入的长度?

This is a strange requirement for a C++ program. 对于C ++程序,这是一个奇怪的要求。 You can of course go the C way and simply keep on getting more memory whenever your input outgrows the currently available memory. 当然,您可以采用C方式,只要输入超出当前可用的内存就可以继续获取更多的内存。 It goes something like this ( warning: code fragments ahead ): 它是这样的( 警告:前面的代码片段 ):

while(cin.get(c)) {
    if (cur_pos == cur_len) {
        cur_len = grow_charbuf(buffer, cur_len);
    }
    buffer[cur_pos++] = c;
}   

Here, the grow function is where it gets ugly. 在这里, grow功能变得很难看。 It needs to allocate a larger piece of memory, copy the contents of the current buffer to the beginning of that, dealocate the memory occupied by the current buffer, and return the new size. 它需要分配更大的内存,将当前缓冲区的内容复制到该缓冲区的开头,重新分配当前缓冲区所占用的内存,并返回新的大小。 For example, something along these lines: 例如,遵循以下原则:

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;
}

And you can then use it as follows: 然后您可以按以下方式使用它:

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

This is terrible code. 这是可怕的代码。 It might work, but you should never ever do this in C++ if you can avoid it. 它可能会起作用,但是如果可以避免,则永远不要在C ++中这样做。 Apart from this, I have avoided handling any error conditions or exceptions that this code might cause. 除此之外,我避免处理此代码可能引起的任何错误情况或异常。 It is meant just to illustrate the idea. 这只是为了说明这个想法。

Managing your memory manually is a bad idea because it requires a lot of code and is not easy to get right. 手动管理内存不是一个好主意,因为它需要大量代码,而且不容易正确使用。 You can get away with less if your program has a known, limited life-span. 如果您的程序的寿命已知有限,那么您可以少花钱。

Don't use characters array at all. 根本不使用字符数组。 Use std::string or other standard containers. 使用std :: string或其他标准容器。 And of cause learn to use streams. 当然要学习使用流。

Here an example. 这里举个例子。 It reads as many characters as the user inputs until the user presses enter. 它读取的字符数与用户输入的字符数相同,直到用户按下Enter键为止。 As you cna see, there is no explicite buffer-size required: 正如您所看到的,不需要显式的缓冲区大小:

/////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

You need a cin.getline(). 您需要一个cin.getline()。 In other words you need to have a specified size of char array and use it like so: 换句话说,您需要具有指定大小的char数组并按如下方式使用它:

Using cin.get() 使用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;

or for cin.getline() 或cin.getline()

char input[100];
cin.ignore(); // stops the sentence from truncating.
cin.getline(input,sizeof(input));

You could also use getline() for strings like so: 您还可以将getline()用于类似这样的字符串:

string name;
getline(cin, name);

The problem is that in c++ when receiving input your cin looks for the 0 aka the space in your sentence. 问题是在c ++中,当接收到输入时,您的cin查找句子中空格(也就是0)。 It then ends thinking that was the end. 然后以为结束就结束了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM