1

I'm using the book C++primer by Stanley B.Lippman and this error is caused by the solution of Excersise 3.2.3 test 3.10.It requires that write a program that reads a string of characters including punctuation and writes what was read but with the punctuation removed.

here's the code:

#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;
}

when I run this code in Visual studio 2017 it shows this:

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.

why it shows like this? I can't understand.

YSC
  • 38,212
  • 9
  • 96
  • 149
Chen
  • 21
  • 5

1 Answers1

2

Although the assertion failure you get is due to a bad call to std::ispunct() (you should iterate over the string with an unsigned char), the proper solution would be to use 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;
}

On a Windows platform, the conjunction of std::wstring1 and std::iswpunct will let you handle Chinese characters right. Note that I assumed your system locale is "zh_CH.UTF-8". If it is not, you'll need to imbue your streams.


1) see this excellent answer about the difference between string and wstring.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • Thank you for your useful answer.I ran this code and there is a small mistake is that 'iswpunct' not std space member.I deleted it and the code can be normal operated.Thank you. – Chen Feb 01 '18 at 07:58