Why does my c++ program output garbled code - c++

I use MinGW64 to compile c++ programs. But since I upgraded to Windows 10, I found my c program output Chinese will be garbled code.
I follow the online method, adding a code in the program header: SetConsoleOutputCP(65001);, then it fixes. but I think it's so troublesome to do this for each c++ program. What should I do?
I think this is my system's problem, the same code in Windows 7 is not a problem, I just want to find a more convenient solution instead of adding the same code to every file
There's the code:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
SetConsoleOutputCP(65001);
cout << "文本" ; //Output will be garbled code if there's no line above
return 0;
}

The console in most operating systems only expects ASCII character input. In order to show some other char set you have to specify that in your code. The SetConsoleOutputCP command sets the "code page" windows should read from. By the way not all versions of windows have the same code for this command.
Please refer to the documentation found here.
The documentation suggests using EnumSystemCodePages to make sure the code for that language exists on that system.
P.S.
Your English is very good :)
EDIT
I tested your code on my computer with Visual Studio 2019 and got the following
Warning C4566 character represented by universal-character-name '\u6587' cannot be represented in the current code page (1255)
even with the SetConsoleOutputCP command you added. I assume you need to have chines installed for this to work. The problem is that I don't have the relevant code page for the windows console to look in for the char set. see this answer and this answer.

Related

How do I fix opening terminal error with c++ ncurses

I'm using CLion 2018.2.6 on MacOS. I'm trying to use ncurses but getting the error "Error opening terminal: unknown." I'm not sure how to fix this. Any help appreciated. Code below.
#include <iostream>
#include <ncurses.h>
using namespace std;
int main(){
initscr();
clear();
printw("Seems legit!");
refresh();
getch();
endwin();
}
The initscr manual page mentions this:
Unset TERM Variable
If the TERM variable is missing or empty, initscr uses the value "unknown", which normally corresponds to a terminal entry with the generic
(gn) capability. Generic entries are detected by setupterm (see
curs_terminfo(3x)) and cannot be used for full-screen operation. Other
implementations may handle a missing/empty TERM variable differently.
Also, depending on how your system is configured, ncurses may not even find the terminal database, e.g., if it is installed in a different location than the compiled-in default location. Like TERM, that can be fixed using the TERMINFO or TERMINFO_DIRS environments. As an additional complication, MacOS by default uses case-insensitive filesystems, and ncurses uses a different directory organization for that. The term(5) manual page mentions that:
A small number of terminal descriptions use uppercase characters in
their names. If the underlying filesystem ignores the difference
between uppercase and lowercase, ncurses represents the "first character" of the terminal name used as the intermediate level of a directory
tree in (two-character) hexadecimal form.
Check the path of terminfo folder in the application running system and the same path in your application like this,
Ex:- setenv("TERMINFO","/usr/share/terminfo", 1);
It working.

in c++, is it possible to / how can i display console output after input, on same line, before user's input is given?

In C++, when writing to and taking information from the console using cout / cin, is it possible to do something like
ENTER YOUR DATA HERE --> __ <-- ENTER YOUR DATA HERE
With the user input cursor where the underscores are located, and output located on either side of the cursor, and then the user's typed input appearing between those two bits of output before being returned to cin?
If so how would I got about doing that?
I hope that between my title and explanation here that it's clear what I'm asking, if not I can try to explain further.
Ideally I'd like to do this using iostream / cin & cout, because those are what I've used in the past. If the solution is to use... printf or similar I'll do that but may need a bit of additional explanation since I'm not really experienced in using that for output.
NOTE: I tried to find an answer for this problem and I can't say for sure that there wasn't one, it was mostly just a matter of finding a huge amount of other input/output-related questions.
EDIT: This is using the DOS shell on Windows 7, compiling from the Windows Visual Studio 2012 command-line compiler.
If Windows, use the Console API. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682073(v=vs.85).aspx
If Linux, use the curses library: http://en.wikipedia.org/wiki/Ncurses
If you are using windows you have the option to use the conio.h.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
gotoxy(5,3);
cout<<"HELLO WORLD";
gotoxy(60,10);
cout<<"HELLO WORLD";
gotoxy(35,20);
cout<<"HELLO WORLD";
getch();
return 0;
}
If you wish to use ANSI libraries only, you can try to take a look at this discussion:
http://www.cplusplus.com/forum/lounge/78225/
In both cases all you have to do is print the first text, then use gotoxy, then you print seconde text, gotoxy again where you want the input to happens, and read the user input.

Beginner questions about vim

Question #1:
if I have a C++ code like this
#include <iostream>
using namesapce std;
int main() {
int a;
cin >> a;
cout << a << endl;
return 0;
}
I don't know if this is called (debugging, compiling, or building), but I just want to run this program inside gvim so I can give it the input and see the output, and see errors such as "missing ';' " or "missing '}' " (like what happens when I click F9 in "Code::Blocks").
exe file, and other things are not important for me.
Question #2:
if I have a C++ code that I write every time like this
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
How can I make vim insert this code every time I open a .cpp file with vim ?
I have Windows 7 32-bit and my .vimrc file is the default one that comes when I install vim.
Please be as detailed as possible.
Probably this is what you are looking for
Vi and Vim Autocommand: 3 Steps to Add Custom Header To Your File Automatically
Q1: You'll need to compile your C++ code first to "see errors such as "missing ';' " or "missing '}'". Then you can run your compiled EXE to determine if your input and output values work. In Visual Studio, hitting the play button (Debug) will do both.
Q2: vim has a set of events that occur that allow you to perform certain actions, like append text to a new file with an extension of .cpp. You would add some code to your .vimrc file to do this.
If you just want it on opening up use autocmd. You can do it like lipun4u said:
Vim autocommand auto add headers at start of file
Well I suggest getting this plugin: snipMate
snipMate.vim aims to be an unobtrusive, concise vim script that implements some of TextMate's snippets features in Vim. A snippet is a piece of often-typed text that you can insert into your document using a trigger word followed by a tab.
It has several features:
More than 1 language supported
Lots of premade snippets
Ability to make your own snippets
So this way you can have different headers for different programs, and just assign them to a hot key.

C++: Unable to resolve identifier cout, Netbeans, Ubuntu

I am using C++ on Netbeans 7.1 on Ubuntu 11.04. For some reason, the following code results in the error message "Unable to resolve identifier cout".
#include <iostream>
using namespace std;
int main()
{
std::cout << "Hello,world!\n";
return 0;
}
Any help resolving this problem would be greatly appreciated.
The solution for your problem is at least strange ;)
Once iostream header is added, one has to reparse code. Click right on a project, go to code assistance and click to reparse project. Worked for me.
I was using netbeans for mac.
check whether iostream is really getting included;
i have tried your code on my machine using eclipse cdt it worked fine.so, please check the
includes.
What sort of file is this in? Is it a .h file, or .hpp file? I had this same issue. Netbeans can be ridiculous sometimes with C++. For me, I changed #include <iostream> to #include<iostream.h>
This may seem too simple, but...
In my NetBeans installation, when I go to create a new project, specify C/C++, it brings up a dialog box prompting for "Project Name:", location, folder, makefile name, and then...
a check box for "Create Main File", an edit box with "main" filled in, and to the right of that is a drop down list that reads "C". If you hit Finish, this will create "main.c" (C, but NOT a C++ file). Instead, in the drop down list, select "C++". Then the IDE creates main.cpp, which will be compiled with g++ and will find those includes and functions.
There is a difference between std::cout and cout. You don't currently have std::cout defined in your file. std::cout is a c standard out. In C++ we only need cout to work with iostream.
If you must use a standard c out then do the following:
Add this to the top under iostream
#include <iostream> //Input output stream in C++
#include <cstdlib> //Stands for c standard library
using namespace std;
Your code will now work because:
This change defines std::cout and std::cin among other things. (standard in, standard out respectively.)
However, I'd recommend this alternative if you don't need standard in outs:
Replace std::cout with cout, because cout is defined in iostream in C++. Your program would have worked without the std:: portion of your cin cout commands because you originally included iostream.
Try taking out the using namespace std; - it's generally considered bad form anyway :-)
I'm not sure that will fix the problem but most people either use the namespace or fully qualify things like std::cout. I've never seen code that does both.
The other thing to check is that the iostream header actually is being bought in. In other words, are there any errors on that line. A lot of problems (at least in the Windows world, so it may not necessarily apply to you) seem to be due to faulty path setup in NetBeans.
Hey look at your Output Debug. You may see "no permission". After I changed the file permission of "/YourProjekt/dist/Debug/GNU-Linux/file" to runable and everyone can read and write the error disappeared. (BTW: I had the bug because I was on a NTFS System with my Projekt, it have to be ext partition)
Hope I can help you with that.
Try taking out the std:: next to cout

swprintf fails with unicode characters in xcode, but works in visual studio

While trying to convert some existing code to support unicode characters this problem popped up. If i try to pass a unicode character (in this case im using the euro symbol) into any of the *wprintf functions it will fail, but seemingly only in xcode. The same code works fine in visual studio and I was even able to get a friend to test it successfully with gcc on linux. Here is the offending code:
wchar_t _teststring[10] = L"";
int _iRetVal = swprintf(_teststring, 10, L"A¥€");
wprintf(L"return: %d\n", _iRetVal);
// print values stored in string to check if anything got corrupted
for (int i=0; i<wcslen(_teststring); ++i) {
wprintf(L"%d: (%d)\n", i, _teststring[i]);
}
In xcode the call to swprintf will return -1, while in visual studio it will succeed and proceed to print out the correct values for each of the 3 chars (65, 165, 8364).
I have googled long and hard for solutions, one suggestion that has appeared a number of times is using a call such as:
setlocale(LC_CTYPE, "UTF-8");
I have tried various combinations of arguments with this function with no success, upon further investigation it appears to be returning null if i try to set the locale to any value other than the default "C".
I'm at a loss as to what else i can try to solve this problem, and the fact it works in other compilers/platforms just makes it all the more frustrating. Any help would be much appreciated!
EDIT:
Just thought i would add that when the swprintf call fails it sets an error code (92) which is defined as:
#define EILSEQ 92 /* Illegal byte sequence */
It should work if you fetch the locale from the environment:
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void) {
setlocale(LC_ALL, "");
wchar_t _teststring[10] = L"";
int _iRetVal = swprintf(_teststring, 10, L"A¥€");
wprintf(L"return: %d\n", _iRetVal);
// print values stored in string to check if anything got corrupted
for (int i=0; i<wcslen(_teststring); ++i) {
wprintf(L"%d: (%d)\n", i, _teststring[i]);
}
}
On my OS X 10.6, this works as expected with GCC 4.2.1, but when compiled with CLang 1.6, it places the UTF-8 bytes in the result string.
I could also compile this with Xcode (using the standard C++ console application template), but because graphical applications on OS X don't have the required locale environment variables, it doesn't work in Xcode's console. On the other hand, it always works in the Terminal application.
You could also set the locale to en_US.UTF-8 (setlocale(LC_ALL, "en_US.UTF-8")), but that is non-portable. Depending on your goal there may be better alternatives to wsprintf.
If you are using Xcode 4+ make sure you have set an appropriate encoding for your files that contain your strings. You can find the encoding settings on a right pane under "Text Settings" group.
Microsoft had a plan to be compatible with other compilers starting from VS 2015 but finally it never happened because of problems with legacy code, see link.
Fortunately you can still enable ISO C (C99) standard in VS 2015 by adding _CRT_STDIO_ISO_WIDE_SPECIFIERS preprocessor macro. It is recommended while writing portable code.
I found that using "%S" (upper case) in the formatting string works.
"%s" is for 8-bit characters, and "%S" is for 16-bit or 32-bit characters.
See: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
I'm using Qt Creator 4.11, which uses Clang 10.