【问题标题】:How I can handle with error about entered size of string exceeds the set size of char array?我如何处理有关输入的字符串大小超过字符数组的设定大小的错误?
【发布时间】:2020-05-17 10:29:50
【问题描述】:

如果我输入的字符串大于设置的大小,我需要某种错误处理程序。

cout << "Enter long of the string" << endl;
        cin >> N;
        char* st = new char[N];
        char* st1 = new char[N];
        for (int i = 0; i < N; ++i) {
            *(st1 + i) = ' ';
        }
        cout << "Enter string in the end put 0,without whitespace in the end." << endl;
        cin.getline(st, N, '0');

【问题讨论】:

  • 为什么不使用 std::string?
  • 接下来我需要逐字拆分字符串,而不是用旧字符串中从 X 到 Y 的单词创建一个新字符串。如果使用 char 数组,我认为它更简单。
  • 你认为你可以用 char 数组做什么,而你不能用 std::string 做什么?

标签: c++ c++11 visual-c++


【解决方案1】:

首先是一些cmets。

  • 不要在 C++ 中使用 C 样式数组(如 char data[N]
  • 字符串始终使用std::string
  • 切勿将 char 数组用于字符串
  • 永远不要在 C++ 中对拥有的内存使用原始指针
  • 几乎永远不要在 C++ 中使用 new
  • 避免使用指向拥有内存的原始指针的指针算法

因此,您应该重新考虑您的设计。首先开始正确地做。

回答你具体问题:如果你阅读getline的文档,那么你可以看到

count-1 个字符已被提取(在这种情况下 setstate(failbit) 被执行)。

因此,将设置故障位。你可以检查一下

if (std::cin.rdstate() == std::ios_base::failbit)

但您也可以在文档中阅读

从流中提取字符直到行尾或指定的分隔符 delim。

因此,它不会像您期望的那样工作,它将尝试读取直到读取 0。我认为它不适合你。

您还需要删除新的内存。否则,您正在创建一个内存漏洞。再看看你的例子并尝试一下:

#include <iostream>

int main() {
    size_t N;
    std::cout << "Enter maximum length of the string\n";
    std::cin >> N;
    char* st = new char[N];
    char* st1 = new char[N];
    for (size_t i = 0U; i < N; ++i) {
        *(st1 + i) = ' ';
    }
    std::cout << "Enter string in the end put 0, without whitespace in the end.\n";
    std::cin.getline(st, N, '0');

    if (std::cin.rdstate() == std::ios_base::failbit) {
        std::cin.clear();
        std::cout << "\nError: Wrong string entered\n\n";
    }

    delete[] st;
    delete[] st1;
    return 0;
}

解决所有问题:使用std::stringstd::getline


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 2019-01-26
    • 2022-06-13
    • 1970-01-01
    • 2021-07-24
    • 2012-10-25
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多