Error screenshot.
I am testing a program to print emoji in C++. My coding environment is Dev C++. But when execute it, it shows a question mark instead of the desired emoji.
Any helpful suggestion to fix my problem would be appreciated.
Here's my code:
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main(void)
{
system("cls");
int sml = 1, i, limit;
char ch = sml;
cout << "How many smiley face you want to print ? ";
cin >> limit;
for (i = 0; i < limit; i++)
{
cout << ch << ' ';
}
return 0;
}
I've got this working for a console app on Windows 11 with the new Terminal and Visual Studio using UTF8. See https://utf8everywhere.org.
You want to make sure the language and the console are set for UTF8:
auto UTF8 = std::locale("en_US.UTF-8");
std::locale::global(UTF8);
std::cout.imbue(UTF8);
setlocale(LC_ALL, "en_us.utf8");
SetConsoleOutputCP(CP_UTF8);
I use std::u8string and entered emojis with Win+.
static std::u8string sDead(u8"🖤");
static std::u8string sLive(u8"😀");
static std::u8string sBorn(u8"💕");
static std::u8string sOld(u8"🤡");
static std::u8string sDying(u8"🤢");
static std::u8string sUnknown(u8"⁉️");
And you need to make sure your files are saved as UTF8 in Visual Studio. Click File, Save As... click the down arrow next to save, and click Save with Encoding...
You also need to make sure your Console and Font support emojis.
Full code is here https://github.com/mgradwohl/TerminalLife
Your program doesn't have any problem, But I can't see the output on vscode. You can also use Unicode and print this: ☺
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
system("cls");
int i, limit;
cout<<"How many smiley face you want to print ? ";
cin>>limit;
for(i=0; i<limit; i++)
{
// Print ☺ in UTF-8
cout << "\342\230\272" << "\t";
}
return 0;
}
The program you've written is correct. It is the console which is at fault. It is unable to print the corresponding character for the ASCII value you've passed. I suggest you change the console (On tips for how to do that, you will have to search on Google).
Take a look at my console output:
Related
I've seen a couple of solutions to this question, but I'm still running into an issue. I've tried several of the solutions I've seen on this site, but I keep having the same issue. I'm not sure how to make this work, and I'm also not sure why it's not working, since I'm really new to C++.
A brief explanation of what I am attempting to do: I'm writing a simple old-school text-based story/game for a video game design club at my school, and at several points I have the user make decisions, or input things such as their name, which is then used in an output line, as it would be referenced several times. I have had no problem doing that, using something simple like this:
#include <iostream>
#include <string>
#include <limits>
#include <windows.h>
using namespace std;
int main(){
string name, place ;
cout << "???: What is your name? ";
getline (cin, name);
cout << "???: Hello, " << name << "!\n" << "\n";
}
My problem is that I'd like to have the text appear one character at a time, like dialogue, but whenever I try to use something I've seen written by others, it doesn't seem to like it very much. The only one that I tried that I can now find again is this:
#include <iostream>
#include <unistd.h> // include <windows.h> on windows
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
usleep(60000); // use Sleep on windows
}
}
int main()
{
type_text("Hej hej hallå!");
}
Apparently there is some sort of conflict regarding my attempt to output the name back to the user when I try to use that code with what I've written. I'm not really sure what the problem is, since I'm so new to C++, can anyone help me out?
Consider using std::this_thread::sleep_for, as it is standard C++11. Example:
#include <iostream>
#include <thread> // standard C++11
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
}
int main()
{
type_text("Hello, World!");
}
If you have access to a C++14 compiler, you can simply make use of the std::chrono user-defined literals and have a more "natural" syntax:
using namespace std::literals;
std::this_thread::sleep_for(60ms);
Previously, I have been interested in learning C++ so I decided to go for "InfiniteSkills" training video (http://www.infiniteskills.com/training/learning-c-plus-plus.html)
The instructor start by teaching "Hello World" as a basic as always.
Here is the code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!";
return 0;
}
but after I build it using CodeBlocks it won't compile
I have also tried using Sublime text too, but the result seems to be the same
Any suggestion?
Image:
you should add a newline character to the end of the line you want to print. Probably you are not seeing your output because it is still in the buffer. As #Quirliom noted: It may not be the stdio buffer but Sublime buffering until new lines...
cout << "Hello, World!\n";
or
cout << "Hello, World!" << endl;
As per the comments, you are unable to see the output. Try this:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!";
cin.get(); // This waits for you to input something and allows you to see the input.
return 0;
}
I don't know the real solution for this problem. But my guess is because of the complier. I have test with CodeBlocks and Sublime Text 3 on mac both won't print "Hello World" for me. So I decided to test with another which is "Xcode" and it works! I don't know what the real problem is but if anyone have any problem like me you may want to try using another complier :)
Thank you everyone for your suggestion and happy coding!!!!
You should both add a newline command in your print function and some sort of pause.
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!\n" //calls for a newline
cin.get(); //pauses until a key is pressed
return 0;
}
Try this and see if it works
I had this problem too but I was able to fix it by reinstalling the C++ plugin for VS Code. I think the iostream wasn't actually there originally.
Here is my code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
ifstream stream;
stream.open("scores.txt");
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failed\n"<<strerror(errno)<<endl;
for(int i=1;i<5;i++)
{
stream>>scores[i];
stream>>names[i];
cout<<i<<endl;
}
cout<<scores[2]<<endl;
stream.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
It get garbage output for scores[2] because stream.open("scores.txt") fails to open a file.
strerror(errno) gives me "No error".
I've checked to see if my file is really called "scores.txt.txt". It is not. I've also tried moving my file to "C:\scores.txt". I've tried using the full address. I've tried deleting it and re-creating it. I've tried other things too that I cannot remember. ![enter image description here][1]I've been trying for hours to fix this and I'm desperate. I'd be grateful if anyone could help me fix this.
void gethighscores is a function that I plan to use later.
The input file looks like this:
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
The output of the program looks like this
It failed
No error
1
2
3
4
-858993460
Press any key to continue . . .
I'm running this in Microsoft Visual Studio Express 2012 for Windows Desktop
My operating system is Windows 7 ultimate 64 bit.
when using the "\" to define a path use two instead of one
C:\ \scores.txt
try this:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
string filename = "scores.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
int scores[32];
string names[32];
int iter = 0;
while (fin >> names[iter] >> scores[iter])
{
if (++iter >= 32 )
{
break;
}
cout << iter << endl;
}
if (iter >= 2)
{
cout << scores[2] << endl;
}
fin.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
Had me stumped for a bit. Your C++ code is reading scores and names in the opposite order from your input text. The first line of text in the input file is Ronaldo, but your first operator>> is to score[0] (an int). This causes the failbit to be set, and so fail() returns true. It also explains why you end up getting garbage for the destination array elements.
Reverse the order of the scores/names in either the scores.txt file or your C++ parsing code (but not both!) and you should be good to go.
The reason it fails is this:
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failed\n"<<strerror(errno)<<endl;
By default, scores[0] and names[0] don't have any set value and it tries to assign them to the file, which causes it to fail. If you try commenting those two lines:
stream>>scores[0];
stream>>names[0];
You'll see that it no longer fails and works fine.
The following code:
#include <iostream>
using std::wcin;
using std::wcout;
using std::locale;
int main()
{
locale::global(locale("Portuguese_Brazil"));
wcout << "wcin Test using \"ção\": "; // shows that wcout works properly
wchar_t wcinTest[] = L"";
wcin >> wcinTest;
wcout << wcinTest << " should be \"ção\".";
return 0;
}
Results in:
wcin Test using "ção": ção
╬Æo should be "ção".
The ╬ character is U+2021 or 8225, and the ç is U+00E7 or 231.
I changed mult-bytes option, set and not set UNICODE in project properties. Nothing worked.
I already set the console font into Consolas, a true type font capable of displaying the ç character correctly.
I'd like this as simple and reproducible possible to use as a standard practice for future UNICODE console applications.
Any ideas?
wcinTest is a wchar_t buffer of length 1;
You overflow it when you read into it. Use a std::wstring insead.
This finally worked:
#include <iostream>
#include <string>
#include <Windows.h>
using std::cin;
using std::cout;
using std::string;
int main()
{
SetConsoleOutputCP(1252);
SetConsoleCP(1252);
cout << "wcin Test using \"ção\": "; // shows that wcout works properly
string wcinTest;
cin >> wcinTest;
cout << wcinTest << " should be \"ção\".";
return 0;
}
I'm too newbie to understand why I need both SetConsoleOutputCP and SetConsoleCP. I though maybe just SetConsoleCP would fix everything, but no, I need both: SetConsoleOutputCP fixed cout; and SetConsoleCP fixed cin.
Thanks anyway #StoryTeller
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
I can't see the russian alpabet in Visual Studio 2008
I'm trying input symbol from console in Russian alphabet. This is code
#include <iostream>
#include <windows.h>
#include <locale.h>
using namespace std;
void main(){
char c;
setlocale(LC_ALL,"rus");
cout << "Я хочу видеть это по-русски!" << endl;
cin >> c;
cout << c;
}
I entered 'ф', but it prints 'д'. I tried to use
char buf[2];
char str[2];
str[0] = c;
str[1] = '\0';
OemToAnsi(buf, str);
But I have
+ str 0x0015fef4 "¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦ф¦¦¦¦d §" char [2]
+ buf 0x0015ff00 "¦¦¦ф¦¦¦¦d §" char [2]
And then I have an error Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.
I assume the set-up you're using is to have the source saved using cp1251 (Cyrillic Windows) and to have the console using cp866 (Cyrillic DOS). (This will be the default set up on Russian versions of Windows.) The problem you're running into seems to be that setting the locale as you do causes output to be converted from cp1251 to cp866, but does not cause the inverse conversion for input. So when you read a character in, the program gets the cp866 representation. This cp866 representation, when output, is incorrectly treated as a cp1251 representation and converted to cp866, resulting in the ф to д transformation.
I think the conversions is just done by the CRT based on the C locale, but I don't know how to enable a similar conversion for input. There are different options for getting your program to work.
Manually convert input data from cp866 to cp1251 before echoing it.
Replace setlocale(LC_ALL,"rus") which changes how the CRT deals with output with calls to SetConsoleCP(1251); SetConsoleOutputCP(1251); which will instead changes the console's behavior (and the changes will persist for the lifetime of the console rather than the lifetime of your program).
Replace uses of cin and cout with Windows APIs using UTF-16. Microsoft's implementation of the standard library forces the use of legacy encodings and causes all sorts of similar problems on Windows. So just avoid it altogether.
Here's an example of the second option:
#include <iostream>
#include <clocale>
#include <Windows.h>
void main(){
char c;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
std::cout << "Я хочу видеть это по-русски!\n";
std::cin >> c;
std::cout << c;
}
Assuming the source is cp1251 encoded then the output will appear correctly and an input ф will not be transformed into a д.
The locale might be wrong. Try
setlocale(LC_ALL, "");
This sets the locale to "the default, which is the user-default ANSI code page obtained from the operating system".
const int N = 34;
const char DosABC[N] = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
const char WinABC[N] = " ЎўЈ¤Ґс¦§Ё©Є«¬®Їабвгдежзийклмноп";
std::string ToDosStr(std::string input)
{
std::string output = "";
bool Ok;
for (unsigned i = 0; i < input.length(); i++)
{
Ok = false;
for (int j = 0; j < N; j++)
if (input[i] == WinABC[j])
{
output += DosABC[j];
Ok = true;
}
if (!Ok)
output += input[i];
}
return output;
}
I did it, and it works, but everybody welcome to find easier answer