[英]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.