简体   繁体   中英

Accepting extended ASCII codes as input in C++

My program is NOT accepting symbols such as "à" considering some city names in the world have these as characters. I'm using C++. I've tried all sort of streams of input such as getline(cin,string), fgets and such. All these forms in gathering input see the special symbols at "...".

This is a windows console application made in visual studio 2015

for example

string funnyChar = "à";
getline(cin, checkFunny);
if (checkFunny.compare(funnyChar) == 0)
//do things

user inputs àero

ALT+0224ero

or user input àero as

ALT+133ero

within the code, the input stream cannot see the alt code inputed as it is, therefor, within my if statement

if(checkFunny.compare(funnyChar)==0)

will never work.

More or less, I need to be able to take in these (any) special characters so I can save them, and then display them later, but also, NOT accept very specific ones such as † (alt+0134)

If you're trying to use those characters in the argument list of the program, that's not possible. main must be declared as either main(void)', 'main(int argc, char **argv)', or the semantic equivalent. I believe you would need something like 'main(int argc, wchar_t **argv)' which is not allowed per the standard.

If you're just trying to process the data after getting it elsewhere, I would say to try the wide char versions of those functions. fgetwc for example. Something like this maybe.

#include <iostream>
#include <string>
int main() {
  std::locale loc("");
  std::locale::global (loc);
  wcin.imbue(loc);
  std::wstring city;
  std::wcout << L"Enter your city: ";
  std::wcin >> city;
  std::wcout << L"What's it like in " << city << "?\n";
}

http://www.cplusplus.com/reference/cwchar/

C++ usually won't encode extended characters in the source (it is generally ASCII, UTF-7). Try

string funnyChar = "\x85";

and it should start working in the way you expect.

Setting stdin and stdout mode to U16 will do the trick. Check the following code. (Note that setting the stdout is only required if you want to out the same character again.)

#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdin), _O_U16TEXT);
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wstring funnyChar(L"à");
    std::wstring checkFunny;
    std::wcin >> checkFunny;
    if (checkFunny.compare(funnyChar) == 0)
        std::wcout << L"Yay" << std::endl;
    std::wcout << checkFunny << std::endl;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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