I'm printing a bunch of strings as following:
cout<<count<<"|"<<newTime.time<<"|"<<newCat<<"|"<<newCon<<endl;
in which count is a counter, newTime.time is a string of time, and newCat and newCon are both strings.
The output is like following:
06:02:11:20:08|DB Mgr|Sending query: “SELECT * FROM users”
Apparently, it left out the count and "|". However, if I change the code into
cout<<count<<"|"<<endl;
cout<<newTime.time<<"|"<<newCat<<"|"<<newCon<<endl;
The output just turned into
2|
06:02:11:20:08|DB Mgr|Sending query: “SELECT * FROM users”
I was first thinking if this is the problem of buffer. I changed endl to flush but the problem still exists.
Thanks for any help.
It sounds like your time string may have a carriage return \r in it. If that's the case, then outputting using your first method will still output the count and separator, but the \r will return to the start of the line and begin overwriting it.
Your second method will not overwrite the count since it's on the previous line (a \r will have little visible effect if you're already at the start of the line).
If you're running on a UNIX-like platform, you can pipe the output through something like od -xcb (a hex dump filter) to see if there is a \r in the output.
Alternatively, if you have a string in your code, you can see if it contains a carriage return with something like:
std::string s = "whatever";
size_t pos = s.find ('\r');
if (pos != std::string::npos) {
// carriage return was found.
}
By way of example, the following program:
#include <iostream>
int main (void) {
std::string s1 = "strA";
std::string s2 = "\rstrB";
std::string s3 = "strC";
std::cout << s1 << '|' << s2 << '|' << s3 << '\n';
std::cout << "=====\n";
std::cout << s1 << '|' << '\n';
std::cout << s2 << '|' << s3 << '\n';
std::cout << "=====\n";
size_t pos = s2.find ('\r');
if (pos != std::string::npos)
std::cout << "CR found at " << pos << '\n';
return 0;
}
seems to output the following:
strB|strC
=====
strA|
strB|strC
=====
CR found at 0
but in fact that first line is actually:
strA|(\r)strB|strC
where (\r) is the carriage return.
And keep in mind you rarely need endl - it's effectively a \n with a flush which is not really necessary in most cases. You can just get away with using \n and let the automated flushing take care of itself.
Related
I am trying to take text input from the user and compare it to a list of values in a text file. The values are this:
That line at the end is the cursor, not a straight line, but it doesn't matter. Anyway, I sort by word and produce the values, then check the values. Semicolon is a separator between words. All the data is basic to get the code working first. The important thing is that all the pieces of data have newlines after them. No matter what I try, I can't get rid of the newlines completely. Looking at the ASCII values shows why, My efforts remove only the new line, but not the carriage return. This is fine most of the time, but when comparing values they won't be the same because the one with the carriage return is treated as longer. Here is the important parts of the code:
int pos = 0;
while (pos != std::string::npos)
{
std::string look = lookContents.substr(pos+1, lookContents.find("\n", pos + 1) - pos);
//look.erase(std::remove(look.begin(), look.end(), '\n'), look.end());
//##
for (int i = 0; i < look.length(); i++)
{
std::cout << (int)(look[i]) << " ";
}
std::cout << std::endl;
std::cout << look << ", " << words[1] << std::endl;
std::cout << look.compare(0,3,words[1]) << std::endl;
std::cout << pos << std::endl;
//##
//std::cout << look << std::endl;
if (look == words[1])
{
std::cout << pos << std::endl;
break;
}
pos = lookContents.find("\n", pos + 1);
}
Everything between the //## are just error checking things. Heres what is outputs when I type look b:2
As you can see, the values have the ASCII 10 and 13 at the end, which is what is used to create newlines. 13 is carriage return and 10 is newline. The last one has its 10 remove earlier in the code so the code doesn't do an extra loop on an empty substring. My efforts to remove the newline, including the commented out erase function, either only remove the 13, or remove both the 10 and 13 but corrupt later data like this:
Also, you can see that using cout to print look and words1 at the same time causes look to just not exist for some reason. Printing it by itself works fine though. I realise I could fix this by just using that compare function in the code to check all but the last characters, but this feels like a temporary fix. Any solutions?
My efforts remove only the new line, but not the carriage return
The newline and carriage control are considered control characters.
To remove all the control characters from the string, you can use std::remove_if along with std::iscntrl:
#include <cctype>
#include <algorithm>
//...
lookContents.erase(std::remove_if(lookContents.begin(), lookContents.end(),
[&](char ch)
{ return std::iscntrl(static_cast<unsigned char>(ch));}),
lookContents.end());
Once you have all the control characters removed, then you can process the string without having to check for them.
int main(){
std::cout << "Insert file name / or path. \n NOTE: ONLY INPUTS. DELETES PREVIOUS DATA.\nV.6" << std::endl;
std::string filen;
std::cin >> filen;
std::ofstream myFile;
try{
myFile.open(filen, std::ios::out);
}
catch(std::fstream::failure){
std::cout << "Could not open file!\n Make sure the name and data type are valid.";
system("pause");
}
while(true){
int press = getch();
if(press == 43) myFile.close();
if(press == 8){myFile << "\b" << " " << "\b";std::cout << "\b" << " " << "\b" << std::flush;}
if(press == 13){ myFile << "\n"; std::cout << "\n" << std::flush;}
if(press != 43 && press != 127 && press != 13 && press != 8){myFile << (char)press;std::cout << (char)press;}
}
return 0;
}
Whenever I choose a text file and I press backspace, and I check the document and when I check the text document, I get random characters like so:
Those are not "random characters"; those are backspace characters! i.e. exactly the input you gave.
This can be verified with a hex editor (or piping the output of your program through hexdump et al).
If you wish to replicate the behaviour of common shells, you'll have to write your own code to identify the backspace character and, instead of appending it to myFile, instead eliminate the previously-entered character.
As #BoundaryImposition pointed out already, writing "\b" to your file, will actually write a binary backspace character to your file. What you probably want instead is myFile.seekp(-1, std::ios_base::cur);. If you are on win/dos machine you likely need extra care with '\n' characters because they are translated into 0x0d 0x0a when written to a text stream (thus they require to seek back 2 positions instead of 1).
But generally, if you are not dealing with very huge files, it will be way easier to just store the content in a std::string (using pop_back or erase, to remove characters if needed) and write it to the file when you are finished.
Why does my C++ program create the strange character shown below in the pictures? The picture on the left with the black background is from the terminal. The picture on the right with the white background is from the output file. Before, it was a "\v" now it changes to some sort of astrological symbol or symbol to denote males. 0_o This makes no sense to me. What am I missing? How can I have my program output just a backslash v?
Please see my code below:
// SplitActivitiesFoo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string s = "foo:bar-this-is-more_text#\venus \"some more text here to read.\"";
vector<string> first_part;
fstream outfile;
outfile.open("out.foobar");
for (int i = 0; i < s.size(); ++i){
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
return 0;
}
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.This is because in the actual program the string will be read in from a file and parsed then sent to another function. I guess I could figure out a way to programmatically add backslashes...
How can I have my program output just a backslash v?
If you want a backslash, then you need to escape it: "#\\venus".
This is required because a backslash denotes that the next character should be interpreted as something special (note that you were already using this when you wanted double-quotes). So the compiler has no way of knowing you actually wanted a backslash unless you tell it.
A literal backslash character therefore has the syntax \\. This is the case in both string literals ("\\") and character literals ('\\').
Why does my C++ program create the strange character shown below in the picture?
Your string contains the \v control character (vertical tab), and the way it's displayed is dependent on your terminal and font. It looks like your terminal is using symbols from the traditional MSDOS code page.
I found an image for you here, which shows exactly that symbol for the vertical tab (vt) entry at value 11 (0x0b):
Also, assume that I do not want to modify my string 's' in this case. I want to be able to parse each character of the string and work around the strange character somehow.
Well, I just saw you add the above part to your question. Now you're in difficult territory. Because your string literal does not actually contain the character v or any backslashes. It only appears that way in code. As already said, the compiler has interpreted those characters and substituted them for you.
If you insist on printing v instead of a vertical tab for some crazy reason that is hopefully not related to an XY Problem, then you can construct a lookup-table for every character and then replace undesirables with something else:
char lookup[256];
std::iota( lookup, lookup + 256, 0 ); // Using iota from <numeric>
lookup['\v'] = 'v';
for (int i = 0; i < s.size(); ++i)
{
cout << "s[" << i << "]: " << lookup[s[i]] << endl;
outfile << lookup[s[i]] << endl;
}
Now, this won't print the backslashes. To undo the string further check out std::iscntrl. It's locale-dependent, but you could utilise it. Or just something naive like:
const char *lookup[256] = { 0 };
s['\f'] = "\\f";
s['\n'] = "\\n";
s['\r'] = "\\r";
s['\t'] = "\\t";
s['\v'] = "\\v";
s['\"'] = "\\\"";
// Maybe add other controls such as 0x0E => "\\x0e" ...
for (int i = 0; i < s.size(); ++i)
{
const char * x = lookup[s[i]];
if( x ) {
cout << "s[" << i << "]: " << x << endl;
outfile << x << endl;
} else {
cout << "s[" << i << "]: " << s[i] << endl;
outfile << s[i] << endl;
}
}
Be aware there is no way to correctly reconstruct the escaped string as it originally appeared in code, because there are multiple ways to escape characters. Including ordinary characters.
Most likely the terminal that you are using cannot decipher the vertical space code "\v", thus printing something else. On my terminal it prints:
foo:bar-this-is-more_text#
enus "some more text here to read."
To print the "\v" change or code to:
String s = "foo:bar-this-is-more_text#\\venus \"some more text here to read.\"";
What am I missing? How can I have my program output just a backslash v?
You are escaping the letter v. To print backslash and v, escape the backslash.
That is, print double backslash and a v.
\\v
I'm trying to output the plaintext contents of this .exe file. It's got plaintext stuff in it like "Changing the code in this way will not affect the quality of the resulting optimized code." all the stuff microsoft puts into .exe files. When I run the following code I get the output of M Z E followed by a heart and a diamond. What am I doing wrong?
ifstream file;
char inputCharacter;
file.open("test.exe", ios::binary);
while ((inputCharacter = file.get()) != EOF)
{
cout << inputCharacter << "\n";
}
file.close();
I would use something like std::isprint to make sure the character is printable and not some weird control code before printing it.
Something like this:
#include <cctype>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("test.exe", std::ios::binary);
char c;
while(file.get(c)) // don't loop on EOF
{
if(std::isprint(c)) // check if is printable
std::cout << c;
}
}
You have opened the stream in binary, which is good for the intended purpose. However you print every binary data as it is: some of thes characters are not printable, giving weird output.
Potential solutions:
If you want to print the content of an exe, you'll get more non-printable chars than printable ones. So one approach could be to print the hex value instead:
while ( file.get(inputCharacter ) )
{
cout << setw(2) << setfill('0') << hex << (int)(inputCharacter&0xff) << "\n";
}
Or you could use the debugger approach of displaying the hex value, and then display the char if it's printable or '.' if not:
while (file.get(inputCharacter)) {
cout << setw(2) << setfill('0') << hex << (int)(inputCharacter&0xff)<<" ";
if (isprint(inputCharacter & 0xff))
cout << inputCharacter << "\n";
else cout << ".\n";
}
Well, for the sake of ergonomy, if the exe file contains any real exe, you'd better opt for displaying several chars on each line ;-)
Binary file is a collection of bytes. Byte has a range of values 0..255. Printable characters that can be safely "printed" form a much narrower range. Assuming most basic ASCII encoding
32..63
64..95
96..126
plus, maybe, some higher than 128, if your codepage has them
see ascii table.
Every character that falls out of that range may, at least:
print out as invisible
print out as some weird trash
be in fact a control character that will change settings of your terminal
Some terminals support "end of text" character and will simply stop printing any text afterwards. Maybe you hit that.
I'd say, if you are interested only in text, then print only that printables and ignore others. Or, if you want everything, then maybe write them out in hex form instead?
This worked:
ifstream file;
char inputCharacter;
string Result;
file.open("test.exe", ios::binary);
while (file.get(inputCharacter))
{
if ((inputCharacter > 31) && (inputCharacter < 127))
Result += inputCharacter;
}
cout << Result << endl;
cout << "These are the ascii characters in the exe file" << endl;
file.close();
I have the following code to open a file and read the data from it, then take the relavent part and print it to screen.
char* search = "model name";
int Offset;
string Cpu;
ifstream CpuInfo;
CpuInfo.open ("/proc/cpuinfo");
if(CpuInfo.is_open())
{
while(!CpuInfo.eof())
{
getline(CpuInfo,Cpu);
if ((Offset = Cpu.find(search, 0)) != string::npos)
{
//cout << "found '" << search << " " << line << endl;
break;
}
}
CpuInfo.close();
}
Cpu.replace (0,13,"");
cout << Cpu
This usually outputs the type of CPU your using, but one problem is that some people have various spaces inbetween the words that it prints out.
My question is how to remove all the spaces from inbetween the words. They can of random ammount and aren't always present.
Thank you in advance.
Since your question states: "how to remove all the spaces from inbetween the words":
You can use std::remove_if from the standard <algorithm> library in addition to std::isspace:
std::string mystring = "Text with some spaces";
std::remove_if(mystring.begin(), mystring.end(), std::isspace);
This now becomes:
Textwithsomespaces
REFERENCES:
http://en.cppreference.com/w/cpp/algorithm/remove