C++ FileIO weird behaviour - c++

While writing a program I came accross a strange behaviour of std::ofstream. Please refer to the code below
ofstream dire;
dire.open("dir.txt", std::ios::out);
// some other code
for(int i=0;i<dir.size();i++)
{
dire << dir[i] << "\t"; // dir is integer vector containing values between 0-9
}
Now when I open dir.txt contents are:
ऴऴऴऴवववववववववशशशशशशशशशशषषषषषषषषरररररररऱऱऱऱऱऱऱऱऱललललललललललललळ.. and so on
if I give a space and then tab(\t) then it works correctly or for that matter \n also works correctly. dire << dir[i] << " \t";
And now the output is:
4 4 4 4 5 5 5 5 5 5.. and so on
I also tried dire.flush() to flush the output buffer to file, but still the same result.
I can definitely get away by using \t but I would like to learn why this is happening.

If you are using Notepad to look at the file then the bug Bush hid the facts can be the problem.
The bug occurs when the string is passed to the Win32 charset detection function IsTextUnicode with no other characters. IsTextUnicode sees what it thinks is valid UTF-16LE Chinese and returns true, and the application then incorrectly interprets the text as UTF-16LE.

Related

output stream in C++ [duplicate]

This question already has answers here:
"std::endl" vs "\n"
(10 answers)
Closed 2 years ago.
If I have opened an output stream like this:
ofstream to(output_file);
How may I print new line (Looking to support different os)?
to << "\n";
to << "" <<endl;
End of line notation, '\n' is used in most of the systems I know except Windows (MS Dos) which use '\r\n'. What is different in between those two is that '\n' in most systems will return cursor to the beggining of new line, where in MS DOS it will go to the same character as previous line, so if you have something like this:
Hello\nWorld!!!
in most systems it will output:
Hello
World!!!
where as in MS DOS it will output:
Hello
World!!!
So to overcome this issue of different systems treating newline differently we have std::endl, which will place correct notation for the correct system. In my code I might be bad, but I am mostly using '\n', but on the other hand I have not been using Windows as my dev machine that much.
One more point, printing out "" is useless.

Vectors in C++ are behaving differently in Windows and Ubuntu

I have to compare two strings which are stored in a vector. Comparison works fine in Windows which uses mingw-g++ compiler(version 4.4.1).
But when I try to do the same in Ubuntu which is running g++ version 4.7.2 I am getting weird problems. I listed them below:
When I try to print the elements individually, they are giving correct output and both strings are same.
But when I try to compare them using == operator or strcmp() it is saying that they are not equal even though they are same.
When I try to print the elements which are compared above some string is replacing first string's value. The code is given below. Ideally the if loop shouldn't be executed, but it is still executing and printing some garbage value instead of v1[i].
vector<string> v1 = r1->GetSchema().GetAttrTypes();
vector<string> v2 = r2->GetSchema().GetAttrTypes();
for(i=0; i<v2.size();i++)
if(v1[i] != v2[i])
cout << v1[i] << " " << v2[i] << " awdsd" << endl;
I don't know what to search for these kind of errors. I am taking strings from same file and storing in vectors in both Windows and Ubuntu.
EDIT: I am attaching part of the code here. The function right side returns vector of strings. I can't paste above classe's code as it is very big code.
The problem has to be in:
r1->GetSchema().GetAttrTypes();
This function must be mucking about with how it's std::string's are created.
Can you show us the code?
Well, everything was just fine, except file from which I am reading input string. Since I created that file on windows, it's End of line is different(\r\n) where as in Ubuntu it is (\n).
In Ubuntu I had to convert the text file I am reading input Unix Mode.
After that everything is fine.
I don't know how I missed this small point.
Thank you for your input.

Automatic cout flushing

Good day,
I wrote a Java program that starts multiple C++ written programs using the Process object and Runtime.exec() function calls. The C++ programs use cout and cin for their input and output. The Java program sends information and reads information from the C++ programs input stream and outputstream.
I then have a string buffer that builds what a typical interaction of the program would look like by appending to the string buffer the input and output of the C++ program. The problem is that all the input calls get appended and then all the output calls get posted. For example, and instance of the StringBuffer might be something like this...
2
3
Please enter two numbers to add. Your result is 5
when the program would look like this on a standard console
Please enter two numbers to add. 2
3
Your result is 5
The problem is that I am getting the order of the input and output all out of wack because unless the C++ program calls the cout.flush() function, the output does not get written before the input is given.
Is there a way to automatically flush the buffer so the C++ program does not have to worry about calling cout.flush()? Similiar to as if the C++ program was a standalone program interacting with the command console, the programmer doesn't always need the cout.flush(), the command console still outputs the data before the input.
Thank you,
In case someone comes looking for a way to set cout to always flush. Which can be totally fair when doing some coredump investigation or the like.
Have a look to std::unitbuf.
std::cout << std::unitbuf;
At the beginning of the program.
It will flush at every insertion by default.
I can't guarantee that it will fix all of your problems, but to automatically flush the stream when you're couting you can use endl
e.g.:
cout << "Please enter two numbers to add: " << endl;
using "\n" doesn't flush the stream, like if you were doing:
cout << "Please enter two numbers to add:\n";
Keep in mind that using endl can be (relatively) slow if you're doing a lot of outputting
See this question for more info

Strange stdout behavior

I'm currently writing a socket program in C++ and I've stumbled across very strange behavior when trying to write to the console (a required task), for some reason.
cout << themsg[0] << themsg[1] << endl;
cout << "Phase 3: Supernode sent the message " << themsg[0] << " on dynamic port number " << themsg[1] << endl;
themsg[0] is the string "User#2:What's up Dick?"
themsg[1] is the string "39416"
The first line should write "User#2:What's up Dick?" to the console, followed by "39416".
The second line should print "Phase 3: Supernode sent the message User#2:What's up Dick? on dynamic port number 39416"
The console output reads as follows:
394162:What's up Dick?
on dynamic port number 39416essage User#2:What's up Dick?
I know that themsg[0] and themsg[1] are correct because I wrote their values to a file for verification. It surely has to be some weird stdout issue.
For the first line it appears the 5 characters of themsg[1] overwrite the first five characters of themsg[0]. For the second line, it appears that the first two parameters for cout are ignored, and then there is a message fragment appended.
If anyone can help, I would really appreciate it. I tried using flush() but to no avail. I'm not really sure how the output buffer works, so I'm really lost with this.
You probably have a carriage return symbol, \r, at the end of themsg[0]. I can reproduce the behavior with the following program on Linux:
int main()
{
std::cout << "User#2: what's up?\r" << "39416" << std::endl;
}
The \r, when not followed by \n, has the effect of returning the virtual "carriage" of the terminal to the beginning of the line, so the next print will overwrite what was already there. You won't see this showing up in a file, though, as the file will just contain both strings including the CR.
Strip off the \r before printing.
I suspect the problem is in your themes variable. I tested your exact setup - and, with proper values, it works correctly. However I then tested the same setup but appended \r to the end of themsg[1] and themsg[2] - and got exactly your behaviour. As your string themsg[1] is coming from the network, it probably has line ending included - and from a different operating system (e.g. UNIX vs Windows) - this is converted to a carriage return without the line feed - resulting in the behaviour you're seeing.

Superscript in C++ console output

I'd like to have my program output "cm2" (cm squared).
How do make a superscript 2?
As Zan said, it depends what character encoding your standard output supports. If it supports Unicode , you can use the encoding for ²(U+00B2). If it supports the same Unicode encoding for source files and standard output, you can just embed it in the file. For example, my GNU/Linux system uses UTF-8 for both, so this works fine:
#include <iostream>
int main()
{
std::cout << "cm²" << std::endl;
}
This is not something C++ can do on its own.
You would need to use a specific feature of your console system.
I am not aware of any consoles or terminals that implement super-script. I might be wrong though.
I was trying to accomplish this task for the purpose of making a quadratic equation solver. Writing ax² inside a cout << by holding ALT while typing 253 displayed properly in the source code only, BUT NOT in the console. When running the program, it appeared as a light colored rectangle instead of a superscript 2.
A simple solution to this seems to be casting the integer 253 as a char, like this... (char)253.
Because our professor discourages us from using 'magic numbers', I declared it as a constant variable... const int superScriptTwo = 253; //ascii value of super script two.
Then, where I wanted the superscript 2 to appear in the console, I cast my variable as a char like this...
cout << "f(x) = ax" << (char)superScriptTwo << " + bx + c"; and it displayed perfectly.
Perhaps it's even easier just to create it as a char to begin with, and not worry about casting it. This code will also print a super script 2 to the console when compiled and run in VS2013 on my Lenovo running Windows 7...
char ssTwo = 253;
cout << ssTwo << endl;
I hope someone will find this useful. This is my first post, ever, so I do apologize in advance if I accidentally violated any Stack Overflow protocols for answering a question posted 5+ years ago. Any such occurrence was not intentional.
Yes, I agree with Zan.
Basic C++ does not have any inbuilt functionality to print superscripts or subscripts. You need to use any additional UI library.
std::cout << cm\x00B2;
writes cm^2.
For super scripting or sub scripting you need to use ascii value of the letter or number.
Eg: Super scripting 2 for x² we need to get the ascii value of super script of 2 (search in google for that) ie - 253. For typing ascii character you have to do alt + 253 here, you can write a any number, but its 253 in this case.
Eg:-cout<<"x²";
So, now it should display x² on the black screen.
Why don't you try ASCII?
Declare a character and give it an ASCII value of 253 and then print the character.
So your code should go like this;
char ch = 253;
cout<<"cm"<<ch;
This will definitely print cm2.