C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组

C++ How to load from the standard input to an array of chars at most 5 alphanumeric characters?

本文关键字:数字字符 数组 字符 标准输入 加载 C++      更新时间:2023-10-16

当我加载少于 5 个字符时,没关系。但是如果我加载超过五个字符,我的程序就会崩溃。在此之前,我该如何保护?

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    char tab[5];
    int tab2[5];
    char *wsk = tab;
    int i = 0;
    cin >> tab;
    while (true)  {
        cin >> tab2[i];
        if (tab2[i] == 0) break;
        i++;
    }
    i = 0;
    while (true) {
        if (tab2[i] ==0) break;
        wsk += tab2[i];
        cout << *wsk;
        i++;
    }
    return 0;
}

您不想将其限制为 5。
您真正想要的是确保读取正常工作并且永远不会崩溃。

您不想在 5 个字符处停止读取的原因是,如果用户输入超过 5 个字符,则您已在其输入过程中停止读取,您现在必须编写代码以找到此输入的末尾,然后继续。编写代码来修复输入流很困难。而是进行输入验证(用户可能键入了废话,您可以生成错误消息),但您将在正确的位置继续阅读下一个输入操作。

char tab[5];
cin >> tab;   // Fails if you read more than 4 input characters
              // (because it will add '' on the end)

为什么不使用自扩展的目标结构。

std::string tab;
std::cin >> tab;  // Read one word whatever the size.

但是阵列呢?
不再困难。在这里,您需要一个重新调整大小的数组。猜猜我们有什么 std::vector

int tab2[5];
while (true)  {
    cin >> tab2[i];  // Fails on the 6 number you input. 
    // STUFF
}

循环可以这样写:

std::vector<int> tab2;
while (true)  {
    int val;
    cin >> val;
    tab2.push_back(val); 
    // STUFF
}

而不是:

while (true)

放:

while (i < 5)

对于 C 样式的数组,您必须将输入流的宽度设置为分配给缓冲区的字符数,否则您可能会写入数组末尾并导致缓冲区溢出。这通常使用ios_base::width完成:

std::cin.width(5);
std::cin >> buffer;

您也可以使用机械手std::setw

std::cin >> std::setw(5) >> buffer;

它们都将流的最大宽度设置为 5 个字符。宽度将在第一次输入操作后重置为其默认值。

您的循环条件应该是

while(i < 5)

此外,for 循环将非常适合

 for(int i = 0; i < 5; i++) {
  // body
 }

您可以使用 STL 的算法部分来绑定读取。例如:

int main(){
    char c[5];
    auto newEnd = std::copy_n(std::istream_iterator<char>(std::cin), 5, std::begin(c));
    // if newEnd != c + 5 then it failed to read 5 characters
}

标准输入是流。你无法决定里面有什么。你所能做的就是从中读取并查看你得到了什么 - 要么你得到一些数据,要么你了解到流已经结束。

如果你真的只想读取五个字节,你可以使用std::cin.read(tab, 5);然后你必须调用std::cin.gcount()来查看实际读取了多少字节,并且只消耗尽可能多的字节。

或者,您可以使用 C++ 的动态容器并使用 std::getline(std::cin, line)std::string line中读取尽可能多的数据,直到换行符。

在任何一种情况下,您首先进行阅读,然后检查您是否实际阅读以及实际阅读了多少,然后检查您阅读的内容是否是您所期望的形式(例如字母数字)。