Console Printing of string and wstring in C++ - c++

I can see there are many questions related to strings and wide strings. But as none of them gives me information I am looking for... I am posting a new question.
I have this code...
std::string myName("vikrant");
std::cout<<myName<<std::endl;
std::wstring myNameHindi = L"मुरुगन";
std::wcout<<myNameHindi<<"-----"<<myNameHindi.size()<<std::endl;
std::wcout<<L"मुरुगन"<<std::endl;
std::string myNameHindiS = "मुरुगन";
std::cout<<myNameHindiS<<"-----"<<myNameHindiS.size()<<std::endl;
when I compile & run this code on my RHEL box(... (connected through ssh, running gcc 4.1.2) I get this o/p (please note middle two lines are not printing properly)
vikrant
.A0A(-----6
.A0A(
मुरुगन-----18
While on my apple laptop and one of FreeBSD(through ssh) box I dont get o/p from w_* code. I just get first and last cout executed
vikrant
मुरुगन-----18
My understanding was that if not specified these strings will be treated as UTF 8. and if string can handle it wstring will handle as well. Is there something wrong in that approach?
Some addon questions are...
is it just a display problem? or wstring is not reliable on linux?
Any additional information may help as well.

EASIEST WAY
Here is what are you looking for, #include <clocale> and for example, to have Turkish, just simply type setlocale(LC_ALL,"Turkish"); to your code.
You can also just leave it as setlocale(LC_ALL,""); it will use your local language.
#include <iostream>
#include <clocale>
int main(){
setlocale(LC_ALL,"Turkish");
std::cout << "I can type any Turkish character like ÖöÇ窺İiĞğÜüİ, anything.\n" << std::endl;
system("pause");
return 0;
}
SOME OTHER WEIRD WAY TO DO IT
This is a really weird way to do it but it will also work.
#include <iostream>
int main()
{
std::string characters="IiĞğÇçÜüŞşÖö";
int i;
for ( i=0; i<characters.length(); ++i ){
characters[i]=(characters[i]==-2) ? 159:characters[i]; //ş
characters[i]=(characters[i]==-3) ? 141:characters[i]; //ı
characters[i]=(characters[i]==-4) ? 129:characters[i]; //ü
characters[i]=(characters[i]==-10) ? 148:characters[i]; //ö
characters[i]=(characters[i]==-16) ? 167:characters[i]; //ğ
characters[i]=(characters[i]==-25) ? 135:characters[i]; //ç
characters[i]=(characters[i]==-34) ? 158:characters[i]; //Ş
characters[i]=(characters[i]==-35) ? 152:characters[i]; //İ
characters[i]=(characters[i]==-36) ? 154:characters[i]; //Ü
characters[i]=(characters[i]==-42) ? 153:characters[i]; //Ö
characters[i]=(characters[i]==-48) ? 166:characters[i]; //Ğ
characters[i]=(characters[i]==-57) ? 128:characters[i]; //Ç
std::cout << characters[i] << " ";
}
}

Related

Unicode Windows console application (WxDev-C++/minGW 4.6.1)

I'm trying to make simple multilingual Windows console app just for educational purposes. I'm using c++ lahguage with WxDev-C++/minGW 4.6.1 and I know this kind of question was asked like million times. I'v searched possibly entire internet and seen probably all forums, but nothing really helps.
Here's the sample working code:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
/* English version of Hello world */
wchar_t EN_helloWorld[] = L"Hello world!";
wcout << EN_helloWorld << endl;
cout << "\nPress the enter key to continue...";
cin.get();
return 0;
}
It works perfectly until I try put in some really wide character like "Ahoj světe!". The roblem is in "ě" which is '011B' in hexadecimal unicode. Compiler gives me this error: "Illegal byte sequence."
Not working code:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
/* Czech version of Hello world */
wchar_t CS_helloWorld[] = L"Ahoj světe!"; /* error: Illegal byte sequence */
wcout << CS_helloWorld << endl;
cout << "\nPress the enter key to continue...";
cin.get();
return 0;
}
I heard about things like #define UNICODE/_UNICODE, -municode or downloading wrappers for older minGW. I tried them but it doesn't work. May be I don't know how to use them properly. Anyway I need some help. In Visual studio it's simple task.
Big thanks for any response.
Apparently, using the standard output streams for UTF-16 does not work in MinGW.
I found that I could either use Windows API, or use UTF-8. See this other answer for code samples.
Here is an answer, not sure this will work for minGW.
Also there are some details specific to minGW here

C++ error too big for character

Here is were i get the error.
To explain, i want to print the → character which according to http://www.endmemo.com/unicode/unicodeconverter.php
The code is 2192. but i may be using the wrong code if so what is the right way to print → .
int _tmain(int argc, _TCHAR* argv[])
{
UINT oldcp = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
cout<<"\x2192"<<endl;
SetConsoleOutputCP(oldcp);
return 0;
}
A char on your platform is 8 bits. Your code part "\x2192" tries to put 16 bits in it. What will not fit, so you get the warning.
You possibly meant several characters, like "\x21\x92" or "\x92\x21"? That creates a valid string with two chars (+ the 0). You may still adjust it to have the proper value if comments are correct.
From the use of _tmain and SetConsoleOutputCP I guess you are mostly about Windows. I'm afraid I don't know much about that; hopefully someone who knows more about that specific case will chime in, but this program generates the output you're looking for in a quick test I tried here with a UTF-8 terminal. Here's the program:
#include <iostream>
int main(void)
{
std::cout << "\xE2\x86\x92" << std::endl;
return 0;
}
And example output:
$ make example && ./example
c++ example.cpp -o example
→
I just directly output the UTF-8 encoding of the → character.
Equivalently (at least for clang):
#include <iostream>
int main(void)
{
std::cout << "→" << std::endl;
return 0;
}

Win32 - Processing the backspace command?

TL;DR I need to know which characters are deleted with Win32.
Basically, I need to know what characters are deleted, each time they are. Considering that there are three methods to delete, (Backspace, delete, and Right click>Delete) I'm not sure if I'll just be re-using the same code or what. There's also the option of multiple characters being selected, as well as the option for undo/redo. There's probably something else I'm missing.
As I said above, I need to know which characters are deleted, and how to use undo/redo and how to tell if when using those if characters were added or deleted. (If that's something easily Google, tell me, I just thought of them as I've been writting this post)
What exactly are you talking about? The win32 default control windows? You can subclass them to do that...
http://msdn.microsoft.com/en-us/library/bb773183%28v=vs.85%29.aspx
Well, if you come up with something specific code-wise and don't quite know what to do, just ask here and see if someone can't help you.
With regard to undo/redo, I believe it all depends on the size of the focus area, and I'm not sure how MS does it for, say, Word, or Excel, etc.
But for short stuff, what I posted above should work in a universal sense, but apparently not in your case.
Nevertheless, if anyone wanted to shorten the iteration in the above, they could replace the loop above by starting right at the end of shorter string, like this --
for(int i = iLen2, x=0; i < iLen1; i++, x++)
szAnswer[x]=str1[i];
This simply confines the interation to the missing characters.
Here is a small Win32 Console application that will demonstrate a very simple way to determine which characters have been deleted. You can easily adapt this to a Win32 App, add iterations to it, and so on
#include <iostream>
#include <string>
using namespace std;
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
int main()
{
int iLen1, iLen2, iResult;
char str1[]="The old red box.";
char str2[]="The old red";
char szAnswer[MAX_PATH]="";
// strcmp() will be greather than 0
// if str1 is longer than str2
if(strcmp(str1, str2) > 0)
{
iLen1=strlen(str1);
iLen2=strlen(str2);
iResult=iLen1-iLen2;
cout << "The number of missing characters is " << iResult << endl << endl;
// now lets see which characters are missing
// we iterate through the entire length
// of str1, which is the full text, but
// we only start puting characters into our
// result when we get to the end of str2
for(int i=0, x=0; i < iLen1; i++)
{
if(i >= iLen2)
{
szAnswer[x++]=str1[i];
}
}
cout << endl << "The missing characters are --" << endl << endl << szAnswer << endl << endl;
}
return 0;
}

Parse int to string with stringstream

Well!
I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution.
I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999].
As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream.
So my code looked like this:
// tempTotal is my int value I want converted.
void toString( int tempTotal, string &str )
{
ostringstream ss; // C++ Standard compliant method.
ss << tempTotal;
str = ss.str(); // Overwrite referenced value of given string.
}
and the function calling it was:
else
{
toString( tempTotal, store );
cout << loop1 << " x " << loop2 << "= " << store << endl;
}
So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there.
Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal.
All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know.
So even though I feel this is a really, really lame question, I just have to ask:
How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.
EDIT:
Wow. Seriously. This is kind of embarrassing. I forgot to set my tempTotal variable to something. It was uninitialized, so therefore I couldn't copy anything and the reason the program gave me either a 0 or nothing at all.
Hope people can have a laugh though, so I think this question would now be better suited for deletion since it doesn't really serve a purpose unless xD But thanks to everybody who tried to help me!
Have you tried just outputting the integer as is? If you're only converting it to a string to output it, then don't bother since cout will do that for you.
else
{
// toString( tempTotal, store ); // Skip this step.
cout << loop1 << " x " << loop2 << "= " << tempTotal << endl;
}
I have a feeling that it's likely that tempTotal doesn't have the value you think it has.
I know this doesn't directly answer your question but you don't need to write your own conversion function, you can use boost
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
//usage example
std::string s = lexical_cast<std::string>(tempTotal);
Try the following:
string toString(int tempTotal)
{
ostringstream ss;
ss << tempTotal;
return ss.str();
}
string store = toString(tempTotal);
If you want to output the integer, you don't even need to convert it; just insert it into the standard output:
int i = 100;
cout << i;
If you want the string representation, you're doing good. Insert it into a stringstream as you did, and ask for it's str().
If that doesn't work, I suggest you minimize the amount of code, and try to pinpoint the actual problem using a debugger :)
Short answer: your method to convert an int to a string works. Got any other questions?

sstream not working...(STILL)

I am trying to get a double to be a string through stringstream, but it is not working.
std::string MatlabPlotter::getTimeVector( unsigned int xvector_size, double ts ){
std::string tv;
ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
It outputs only "0:" on my console...
I'm working on two projects, both with the same problem. I'm posting a different one, which runs into the same problem. It is posted here:
http://pastebin.com/m2dd76a63
I have three classes PolyClass.h and .cpp, and the main. The function with the problem is PrintPoly. Can someone help me out? Thanks a bunch!!
You're printing correctly, however your logic in the order of printing is incorrect.
I modified it to work they way I think you wanted it to, let me know if this helps.
http://pastebin.com/d3e6e8263
Old answer:
Your code works, though ostringstream is in the std namespace. The problem is in your file printing code.
Can I see your call to the function?
I made a test case:
// #include necessary headers
int main(void)
{
std::string s;
s = MatlabPlotter::getTimeVector(1,1.0);
}
The output I get is 0:1:1
The following code is 100% correct:
#include <iostream>
#include <sstream>
#include <string>
// removed MatlabPlotter namespace, should have no effect
std::string getTimeVector(unsigned int xvector_size, double ts)
{
// std::string tv; // not needed
std::ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
int main(void)
{
// all work
// 1:
getTimeVector(0, 3.1415);
// 2: (note, prints twice, once in the function, once outside)
std::cout << getTimeVector(0, 3.1415) << std::endl;
// 3: (note, prints twice, once in the function, once outside)
std::string r = getTimeVector(0, 3.1415);
std::cout << r << std::endl;
}
Find where we differ, that's likely your source of error. Because it stops at your double, I'm guessing the double you're trying to print is infinity, NaN (not a number), or some other error state.
I can't really help with the "no output" part of this, as you didn't show your code that tries to output this. As a guess, did you perhaps not put an EOL in there somehow? Some systems won't give any text output until they hit a newline. You can do this by tacking a << std::endl onto your line, or a '\n' to your string.
Since you didn't put down a using for it, you need to use the type std::ostringstream. This is similar to how you had to use "std:string" instead of just "string".
Also, were it me, I'd get rid of that temp variable and just return ss.str(); It is less code (to possibly get wrong), and probabaly less work for the program.
Well, I tried the code you linked to and it outputs
B 4
A 5
B 4
C 3
x^ + 5x^ + 3
for me before crashing although the crash happens after PrintPoly. From looking at the code this is what I'd expect it to print. Are you saying you get no integers appearing after the letters?
Thanks all for your input! Not sure of the exact error, but it must be some setting in XCode which is messing it up. I made a CMakeLists.txt file and compiled it from the terminal using
cmake -G XCode ..
and produced an XCode project. I ran it, and now it works fine...now would anyone happen to know what might cause XCode to do this? I'm running version 3.2 with the following:
64-bit
Component versions
Xcode IDE: 1610.0
Xcode Core: 1608.0
ToolSupport: 1591.0