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

Creating an error message if user inputs too many characters

我对编码还很陌生,所以如果这是微不足道的,我深表歉意。当用户输入的字符多于我的 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 语句。

iostream.get()(此处调用为 cin.get())读取确切的字节数,然后结束。在您的情况下,它绝对不会将超过 SIZE2 个字节读入 major;结果,if(majorLength > SIZE2) 将始终为假。此外,如果您输入的字节过多,major 将只包含前 20 个字节 - 其余的将被 t运行 处理。 (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