【问题标题】:Assertion failure in std::ispunct in a simple program简单程序中 std::ispunct 中的断言失败
【发布时间】:2018-02-01 18:50:42
【问题描述】:

我正在使用 Stanley B.Lippman 的 C++primer 一书,此错误是由 Excersise 3.2.3 test 3.10 的解决方案引起的。它需要编写一个程序来读取包括标点符号在内的字符串并写入阅读的内容,但删除了标点符号。

代码如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {
  string s;
  cout << "Please input a string of characters including punctuation:" << endl;
  getline(cin, s);
  for (auto c : s) {
     if (!ispunct(c))
         cout << c;
  }
  cout << endl;

 return 0;
}

当我在 Visual Studio 2017 中运行此代码时,它会显示:

Debug Assertion failed.
Expression:c>=-1&&c<=255
For information on how your program can cause an assertion failure,see the Visual C++ documentation on asserts.

为什么会这样显示?看不懂。

【问题讨论】:

  • 它的断言在哪一行? (添加评论向我们展示),另外,您的意见是什么?
  • 您的字符中可能有一个不是 ASCII 码?
  • 向我们展示您的意见!
  • 试试for (unsigned char c : s)
  • @manni66 好点 - 更多解释为什么 - 在这里:en.cppreference.com/w/cpp/string/byte/ispunct

标签: c++ c++11


【解决方案1】:

虽然您得到的断言失败是由于对std::ispunct() 的错误调用(您应该使用unsigned char 迭代字符串),但正确的解决方案是使用std::iswpunct

#include <iostream>
#include <string>
#include <locale>
#include <cwctype> // std::iswpunct

int main()
{
    std::wstring s;
    do {
        std::wcout << "Please input a string of characters including punctuation:\n";
    } while (!std::getline(std::wcin, s));

    for (auto c : s) {
        if (!std::iswpunct(c))
            std::wcout << c;
    }
    std::wcout << std::endl;
}

在 Windows 平台上,std::wstring1std::iswpunct 的结合可以让您正确处理汉字。请注意,我假设您的系统语言环境是"zh_CH.UTF-8"。如果不是,您需要imbue您的信息流。


1)看到这个关于the difference between string and wstring的优秀答案。

【讨论】:

  • 感谢您的有用回答。我跑了这段代码,有个小错误是'iswpunct'不是std空间成员。我删除了它,代码可以正常运行。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
相关资源
最近更新 更多