How can print raw escape characters as \t and \n in cout? - c++

how can print escape characters without further processing and as \t or \n or ... in std::cout?
I dont want to process text manually before sending it to output?
Is there any switch to std::cout for this purpose?

Basically a raw string literal is a string in which the escape characters (like \n \t or \" ) of C++ are not processed. A raw string literal starts with R"( and ends in )", let's see it in an example the difference between a normal string and a raw string in C++:
string raw_str=R"(First line.\nSecond line.\nEnd of message.\n)";
cout<<raw_str<<endl;
result:
~$ ./a.out
First line.\nSecond line.\nEnd of message.\n

If you add one extra slash there as \\t you can see \t in the output of std::cout
For example: cout<<"\\t hello" will print \t hello.
I hope this helps

Related

Trying to remove newlines and carriage returns from a text. Why doesn´t this code work? [duplicate]

I have a text in a textarea and I read it out using the .value attribute.
Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?
If that is not possible, is there another way?
How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \n and Apple uses \r.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
Line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)
Therefore, the most efficient RegExp literal to match all variants is
/\r?\n|\r/
If you want to match all newlines in a string, use a global match,
/\r?\n|\r/g
respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)
var str = " \n this is a string \n \n \n"
console.log(str);
console.log(str.trim());
String.trim() removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
You can use \n in a regex for newlines, and \r for carriage returns.
var str2 = str.replace(/\n|\r/g, "");
Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n';
str = str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"
.replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters:
[ \f\n\r\t\v​\u00a0\u1680​\u2000​-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
If you want to remove all control characters, including CR and LF, you can use this:
myString.replace(/[^\x20-\x7E]/gmi, "")
It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.
This will replace the line break by empty space.
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
Read more on this article.
var str = "bar\r\nbaz\nfoo";
str.replace(/[\r\n]/g, '');
>> "barbazfoo"
To remove new line chars use this:
yourString.replace(/\r?\n?/g, '')
Then you can trim your string to remove leading and trailing spaces:
yourString.trim()
USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
In the above expression, g and m are for global and multiline flags
I often use this regex for (html) strings inside jsons:
replace(/[\n\r\t\s]+/g, ' ')
The strings come from a html editor of a CMS or a i18n php. The common scenarios are:
- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
ipsum
- lorem ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r
The regex avoids this ugly things:
lorem\nipsum => loremipsum
lorem,\nipsum => lorem,ipsum
lorem,\n\nipsum => lorem, ipsum
...
Surely not for all use cases and not the fastest one, but enough for most textareas and texts for websites or webapps.
The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.
The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.
If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.
// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
const LF = `\u{000a}`; // Line Feed (\n)
const VT = `\u{000b}`; // Vertical Tab
const FF = `\u{000c}`; // Form Feed
const CR = `\u{000d}`; // Carriage Return (\r)
const CRLF = `${CR}${LF}`; // (\r\n)
const NEL = `\u{0085}`; // Next Line
const LS = `\u{2028}`; // Line Separator
const PS = `\u{2029}`; // Paragraph Separator
const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
for (let lineTerminator of lineTerminators) {
if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
finalString = finalString.replace(regex, replacementString); // perform the replacement
};
};
return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
Simple we can remove new line by using text.replace(/\n/g, " ")
const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);
var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
A linebreak in regex is \n, so your script would be
var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));
I am adding my answer, it is just an addon to the above,
as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:
var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
Try the following code. It works on all platforms.
var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';
break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'
If it happens that you don't need this htm characte &nbsp shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');
cheers
1st way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.replace(/(\r\n|\n|\r)/gm, "");
2nd way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.split('\n').join('');
On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.
On windows, it will be \r\n.
This will remove all your newlines, spaces, unnecessary characters
str = '\n \n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n Books\n \n \n \n \n\n\n'
console.log(str)
var output = str.replace(/\n|\r|\W/g, "");
console.log(output)
'Books'
const text = 'test\nwith\nline\nbreaks'
const textWithoutBreaks = text.split('\n').join(' ')

Using one cout command to print multiple strings with each string placed on a different (text editor) line

Take a look at the following example:
cout << "option 1:
\n option 2:
\n option 3";
I know,it's not the best way to output a string,but the question is why does this cause an error saying that a " character is missing?There is a single string that must go to stdout but it just consists of a lot of whitespace charcters.
What about this:
string x="
string_test";
One may interpret that string as: "\nxxxxxxxxxxxxstring_test" where x is a whitespace character.
Is it a convention?
That's called multiline string literal.
You need to escape the embedded newline. Otherwise, it will not compile:
std::cout << "Hello world \
and stackoverflow";
Note: Backslashes must be immediately before the line ends as they need to escape the newline in the source.
Also you can use the fun fact "Adjacent string literals are concatenated by the compiler" for your advantage by this:
std::cout << "Hello World"
"Stack overflow";
See this for raw string literals. In C++11, we have raw string literals. They are kind of like here-text.
Syntax:
prefix(optional) R"delimiter( raw_characters )delimiter"
It allows any character sequence, except that it must not contain the
closing sequence )delimiter". It is used to avoid escaping of any
character. Anything between the delimiters becomes part of the string.
const char* s1 = R"foo(
Hello
World
)foo";
Example taken from cppreference.

how can I print "\' in c++?

I have a homework assignment where part of the menu has to have "R\C" printed, but when I run the program the console just prints "RC". Does anyone know why is this happening and how I can fix it?
This is what I have in Visual Studio:
cout << "R\C" << endl;
The \C is being interpreted as an (invalid) escape sequence. You need to escape the \ character as \\ in order to print it as a single \, eg:
cout << "R\\C" << endl;
Alternatively, in C++11 and later, you can use a raw string literal instead, so you do not need to escape the \ character:
cout << R"(R\C)" << endl;
Escape \ with another \:
cout << "R\\C" << endl;
c++ reserve some characters, so you can't directly input them, usually you will have to put \ in front of them to signify that you want to use "\" as a string.
You have to use escape sequences for certain characters. For the character that you specified you would have to output as “\\” and your output would be \. Other escape sequences are:
\’
\t For Tab
\n For newline
\? For question marks
See this for more information.
You can use escape sequences.., like \t, \n, \a...
If you want to print ' \ ', you have to code like this
cout<<"\\";

Print a string like "First\nSecond" on two lines

Aim: to read a string in the form First\nSecond from a file and to print it as
First
Second
Problem: if the string is defined in the code, as in line = "First\nSecond";, then it is printed on two lines; if instead I read it from a file then is printed as
First\nSecond
Short program illustrating the problem:
#include "stdafx.h" // I'm using Visual Studio 2008
#include <fstream>
#include <string>
#include <iostream>
void main() {
std::ifstream ParameterFile( "parameters.par" ) ;
std::string line ;
getline (ParameterFile, line) ;
std::cout << line << std::endl ;
line = "First\nSecond";
std::cout << line << std::endl ;
return;
}
The parameters.par file contains only the line
First\nSecond
The Win32 console output is
C:\blabla>SOtest.exe
First\nSecond
First
Second
Any suggestion?
In C/C++ string literals ("...") the backslash is used to mark so called "escape sequences" for special characters. The compiler translates (replaces) the two characters '\' (ASCII code 92) followed by 'n' (ASCII code 110) by the new-line character (ASCII code 10). In a text file one would normally just hit the [RETURN] key to insert a newline character. If you really need to process input containing the two characters '\' and 'n' and want to handle them like a C/C++ compiler then you must explicitely replace them by the newline character:
replace(line, "\\n", "\n");
where you have to supply a replace function like this:
Replace part of a string with another string (Standard C++ does not supply such a replace function by itself.)
Other escape sequences supported by C/C++ and similar compilers:
\t -> [TAB]
\" -> " (to distinguish from a plain ", which marks the end of a string literal, but is not part of the string itself!)
\\ -> \ (to allow having a backslash in a string literal; a single backslash starts an escape sequence)
The character indicated in a string literal by the escape sequence \n is not the same as the sequence of characters that looks like \n!
When you think you're assigning First\nSecond, you're not. In your source code, \n in a string literal is a "shortcut" for the invisible newline character. The string does not contain \n - it contains the newline character. It's automatically converted for you.
Whereas what you're reading from your file is the actual characters \ and n.

Tokenize a string based on quotes

I am trying to read data from a text file and split the read line based on quotes. For example
"Hi how" "are you" "thanks"
Expected output
Hi how
are you
thanks
My code:
getline(infile, line);
ch = strdup(line.c_str());
ch1 = strtok(ch, " ");
while (ch1 != NULL)
{
a3[i] = ch1;
ch1 = strtok(NULL, " ");
i++;
}
I don't know what to specify as delimiter string. I am using strtok() to split, but it failed. Can any one help me?
Please have a look at the example code here. You should provide "\"" as delimiter string to strtok.
For example,
ch1 = strtok (ch,"\"");
Probably your problem is related with representing escape sequences. Please have a look here for a list of escape sequences for characters.
Given your input: "Hi how" "are you" "thanks", if you use strtok with "\"" as the delimiter, it'll treat the spaces between the quoted strings as if they were also strings, so if (for example) you printed out the result strings, one per line, surrounded by square brackets, you'd get:
[Hi how]
[ ]
[are you]
[ ]
[thanks]
I.e., the blank character between each quoted string is, itself, being treated as a string. If the delimiter you supplied to strtok was " \"" (i.e., included both a quote and a space) that wouldn't happen, but then it would also break on the spaces inside the quoted strings.
Assuming you can depend on every item you care about being quoted, you want to skip anything until you get to a quote, ignore the quote, then read data into your input string until you get to another quote, then repeat the whole process.