如果用户输入太多字符,则创建错误消息

问题描述 投票:-2回答:1

我对编码非常陌生,如果这很简单,我深表歉意。当用户输入的字符多于我的const int SIZE2数组(20个字符)时,我应该创建一条错误消息。我的数组叫做major

>cout << "Enter your major: " << endl << endl;
>48         cin.width(SIZE2);
>49         cin.get(major,SIZE2, '\n');
>50         majorLength = strlen(major);
>51         
>52         if(majorLength > SIZE2)
>53         {   
>54             cout << "Too many characters, Enter major again: " << endl;
>55             cin.get(major, SIZE2, '\n');
>56             cin.ignore(100, '\n');
>57          
>58         }

它的编译很好,但是跳过了我的if语句。

c++ cin c-strings
1个回答
1
投票

iostream.get()(在此称为cin.get())读取确切的字节数,然后结束。在您的情况下,它明确地永远不会读入SIZE2以上的major个字节;结果,if(majorLength > SIZE2)将始终为假。另外,如果输入太多字节,major将仅具有前20个字符-其余的将被截断。 (FWIW,您的代码现在仅匹配19个字符。)

请注意,您probably shouldn't try to do this-在阅读流之前,实际上没有一种很好的方法来检查流的长度,如果您决定只阅读它并检查其大小,则会冒风险缓冲区溢出的原因-假定其大小是固定的。但是,您可以在读取后确定缓冲区是否为空。要确定缓冲区中SIZE2以外是否还有其他输入,可以使用std::cin.get()捕获一个字符,然后检查该字符。如果字符为\n,则表示缓冲区中没有更多输入;如果不是,则表示字符缓冲区中的输入过多。如果输入完全为空,这也会触发。

#include <iostream> int main () { int SIZE2 = 20; char str[SIZE2]; char c; std::cin.get (str, SIZE2+1); // get c-string of 20 chars std::cin.get(c); //get last buffer character if(c != '\n') { std::cout << "bad input!" << std::endl; } std::cout << str << std::endl; return 0; }

Demo
© www.soinside.com 2019 - 2024. All rights reserved.