简体   繁体   English

那是C ++编译器错误吗?

[英]Is that C++ compiler error?

I got some troubles trying to execute following code: 我在尝试执行以下代码时遇到了一些麻烦:

#include <iostream>
#include <regex>

int main(int argc, char** argv) {

    std::wstring buffer; // Buffer string for input

    std::wregex integerRegex(L"^-?[0-9]+$"); // Regex for integers (123, -123, etc.)

    while (true) {

        std::wcout << L"Enter your value:\n";
        std::wcin >> buffer; // Input string from keyboard to determinate is it integer or not

        // Check if integer or not
        if (regex_match(buffer, integerRegex)) {

            std::wcout << L"Integer!\n";

        } else {

            std::wcout << L"Unknown :(\n";

        }
    }

    return 0;
}

This code should output Integer! 此代码应输出Integer! if entered sequence is integer or Unknown :( if not. But in some case I got false-positive results: When I enter something like: -234а , where а is cyrillic character - the code above say's it's integer, but it's not. Other cyrillic characters are not making such troubles. 如果输入的序列是整数或Unknown :(如果不是。但是在某些情况下,我得到的是假阳性结果:当我输入-234а ,其中а是西里尔字符-上面的代码说是整数,但不是。西里尔字母不会造成这种麻烦。

Compiler is TDM-GCC 5.1.0 Compiled with following flags: 编译器为TDM-GCC 5.1.0,编译时带有以下标志:

-std=c++11 -w -Wall -Wextra -pedantic -Werror -pg -pipe

Can someone explain what is the root of problem and who's wrong? 有人可以解释问题的根源是谁吗?

It seems wcin is trying to read the input as ASCII. 似乎wcin试图将输入读取为ASCII。 The non-ASCII characters cause it to get into an exception state. 非ASCII字符使它进入异常状态。 Adding something like the following should solve it: 添加类似以下内容的内容可以解决该问题:

std::setlocale(LC_ALL, "C.UTF-8");

Or on Windows: 或在Windows上:

SetConsoleCP(CP_UTF8);

Here is some more information: What most correct way to set the encoding in C++? 这里是一些更多信息: 在C ++中设置编码的最正确方法是什么?

However, as mentioned by someone in the above post, you shouldn't really be modifying the locale like that. 但是,正如以上博文中提到的那样,您实际上不应该那样修改语言环境。 Instead you should be working with whatever locale is set. 相反,您应该使用任何设置的语言环境。 To use this information, you can use: 要使用此信息,可以使用:

std::setlocale(LC_ALL, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM