Same Command Over Several Lines in C++ [duplicate] - c++

This question already has answers here:
C++ multiline string literal
(10 answers)
Closed 9 years ago.
I want to write a single variable over several lines in C++. more precisely in WINAPI.
Something like: (if \ is the command that does it,)
str=" This is a sample file trying to write multiple lines. \n but it is not same as line break. \
I am defining the same string over several lines. This is different from using backslash n. \
This is not supposed to print multipline in screen or in write file or on windows display. This\
is for ease of programming.";
The problem with this is that I got "|||" whereever I had used \ in my code. I don't want that to appear.
What shall I do?

There are several alternatives. Here are two:
Put the content of the string into a file and read the file content into the string. When you find yourself using lots of long strings, this probably the “correct” way.
Use the following syntax:
str = "This is a string that is going over several lines "
"but it does not include line breaks and if you print "
"the string you will see that it looks like it was "
"written normally.";
– C++ allows you to write several string literals after another and concatenates them automatically at compile time. That is, "a" "b" is the same as "ab", as far as C++ is concerned.

Related

[Regex]::Match() behaving differently inside vs outside an If (that also uses [Regex]::Match() ) [duplicate]

This question already has answers here:
Execute "real life" command line from variable in Powershell
(3 answers)
Closed 4 years ago.
Given a uninstallString of "C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe" /uninstall I can successfully extract the quoted text with ([Regex]::Match($uninstallString, '^\".*\"').Value). however, if I test to see if the string has the required /uninstall bit, then try to extract the quoted bit, like this...
if ([Regex]::Match($uninstallString, '^\".*\" +/uninstall').Succes) {
([Regex]::Match($uninstallString, '^\".*\"').Value)
}
Instead of the value being the full string, it's only returning "C:\ProgramData\Package. Now, My understanding is that . is everything but a line break, so it should be OK with the space. But, if I replace the space with an underscore in the string it works as expected, so it's definitely the space causing the issue.
Also, I am confused why it works outside of the If, but not inside. I was under the impression that using [Regex]::Match() creates individual objects with each use, that wouldn't interact with each other, but here it seems they are.
Since you want to see if the quoted string (path) is found AND if it contains a switch '/uninstall' or not,
I'd do something like this:
$uninstallString = '"C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe"'
if ($uninstallString -match '^(?<path>".*")(?:\s+(?<switch>/uninstall))?') {
$uninstallPath = $matches['path'] # at least the path (quoted string) is found
$uninstallSwitch = $matches['switch'] # if '/uninstall' switch is not present, this will result in $null
}

Convert a list (.txt file) into an array form [duplicate]

This question already has an answer here:
c++ how to build a 2D matrix of strings from a .dat file? 5 columns x rows
(1 answer)
Closed 8 years ago.
Say that I have a .txt file with 5000 words one above the other. and I want to convert that list contained in the txt file into this form:
{"word1, "word2", "word3" ....."word5000"}
So that way I can use it as an array for C++.
Is there a way to do that? Any method is welcome , as long as it is an automated process. Thanks for reading!
Use a vector instead of an array. Using it, the task looks something like this:
std::ifstream in("words.txt");
std::vector<std::string> words{ std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>() };
Now the word that was on the first line of the file is in words[0], the second in words[1], and so on.
Note: if a line contains more than one word, this will read them as separate words. If you want the entire contents of a line treated as a single word, see the answers to a previous question specifically about how to do that.

Including files as raw string literals [duplicate]

This question already has answers here:
"#include" a text file in a C program as a char[]
(21 answers)
Closed 9 years ago.
I have a C++ source file and a Python source file. I'd like the C++ source file to be able to use the contents of the Python source file as a big string literal. I could do something like this:
char* python_code = "
#include "script.py"
"
But that won't work because there need to be \'s at the end of each line. I could manually copy and paste in the contents of the Python code and surround each line with quotes and a terminating \n, but that's ugly. Even though the python source is going to effectively be compiled into my C++ app, I'd like to keep it in a separate file because it's more organized and works better with editors (emacs isn't smart enough to recognize that a C string literal is python code and switch to python mode while you're inside it).
Please don't suggest I use PyRun_File, that's what I'm trying to avoid in the first place ;)
The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.
You could preprocess script.py into something like:
"some code\n"
"some more code that will be appended\n"
and #include that, however. Or you can use xxd​ -i to generate a C static array ready for inclusion.
This won't get you all the way there, but it will get you pretty damn close.
Assuming script.py contains this:
print "The current CPU time in seconds is: ", time.clock()
First, wrap it up like this:
STRINGIFY(print "The current CPU time in seconds is: ", time.clock())
Then, just before you include it, do this:
#define STRINGIFY(x) #x
const char * script_py =
#include "script.py"
;
There's probably an even tighter answer than that, but I'm still searching.
The best way to do something like this is to include the file as a resource if your environment/toolset has that capability.
If not (like embedded systems, etc.), you can use a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It'll take a file's binary representation and spit out a C source file that includes an array of bytes initialized to that data. You might need to do some tweaking of the tool or the output file if you want the array to be '\0' terminated.
Incorporate running the bin2c utility into your makefile (or as a pre-build step of whatever you're using to drive your builds). Then just have the file compiled and linked with your application and you have your string (or whatever other image of the file) sitting in a chunk of memory represented by the array.
If you're including a text file as string, one thing you should be aware of is that the line endings might not match what functions expect - this might be another thing you'd want to add to the bin2c utility or you'll want to make sure your code handles whatever line endings are in the file properly. Maybe modify the bin2c utility to have a '-s' switch that indicates you want a text file incorportated as a string so line endings will be normalized and a zero byte will be at the end of the array.
You're going to have to do some of your own processing on the Python code, to deal with any double-quotes, backslashes, trigraphs, and possibly other things, that appear in it. You can at the same time turn newlines into \n (or backslash-escape them) and add the double-quotes on either end. The result will be a header file generated from the Python source file, which you can then #include. Use your build process to automate this, so that you can still edit the Python source as Python.
You could use Cog as part of your build process (to do the preprocessing and to embed the code). I admit that the result of this is probably not ideal, since then you end up seeing the code in both places. But any time I see the "Python," "C++", and "Preprocessor" in closs proximity, I feel it deserves a mention.
Here is how automate the conversion with cmd.exe
------ html2h.bat ------
#echo off
echo const char * html_page = "\
sed "/.*/ s/$/ \\n\\/" ../src/page.html | sed s/\"/\\\x22/g
echo.
echo ";
It was called like
cmd /c "..\Debug\html2h.bat" > "..\debug\src\html.h"
and attached to the code by
#include "../Debug/src/html.h"
printf("%s\n", html_page);
This is quite system-dependent approach but, as most of the people, I disliked the hex dump.
Use fopen, getline, and fclose.

C++ new line not translating

First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");
it does come out as separate lines in the other end, but if I retrieve the text from the app using a method that returns a const char then pass it straight to printInApp (which takes const char as argument), it comes out as a single line.
Why's this and how would I go about to fix it?
It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), you will need to write (or use an existing one) a string function which finds the escape codes and converts them to other values, eg converting a '\' followed by a 'n' into a newline (ascii value 10).

Incorporating text files in applications?

Is there anyway I can incorporate a pretty large text file (about 700KBs) into the program itself, so I don't have to ship the text files together in the application directory ? This is the first time I'm trying to do something like this, and I have no idea where to start from.
Help is greatly appreciated (:
Depending on the platform that you are on, you will more than likely be able to embed the file in a resource container of some kind.
If you are programming on the Windows platform, then you might want to look into resource files. You can find a basic intro here:
http://msdn.microsoft.com/en-us/library/y3sk7e6b.aspx
With more detailed information here:
http://msdn.microsoft.com/en-us/library/zabda143.aspx
Have a look at the xxd command and its -include option. You will get a buffer and a length variable in a C formatted file.
If you can figure out how to use a resource file, that would be the preferred method.
It wouldn't be hard to turn a text file into a file that can be compiled directly by your compiler. This might only work for small files - your compiler might have a limit on the size of a single string. If so, a tiny syntax change would make it an array of smaller strings that would work just fine.
You need to convert your file by adding a line at the top, enclosing each line within quotes, putting a newline character at the end of each line, escaping any quotes or backslashes in the text, and adding a semicolon at the end. You can write a program to do this, or it can easily be done in most editors.
This is my example document:
"Four score and seven years ago,"
can be found in the file c:\quotes\GettysburgAddress.txt
Convert it to:
static const char Text[] =
"This is my example document:\n"
"\"Four score and seven years ago,\"\n"
"can be found in the file c:\\quotes\\GettysburgAddress.txt\n"
;
This produces a variable Text which contains a single string with the entire contents of your file. It works because consecutive strings with nothing but whitespace between get concatenated into a single string.