How to put a new line inside a string in C++? - string

I was thinking if it is possible to make a string in C++ which contains data in it like, I don't want to make a string of strings or an array of strings.
Suppose I have a string mv:
mv =
"hello
new
world "
"hello", "new" and "world" are in different lines. Now if we print mv, then "hello", "new" and "world" should come on different lines.
I was also thinking with respect to competitive programming. If I concatenate all the answers of queries in a single string and then output the answer, or cout all the queries one by one, will there be a time difference in both the outputs?

i want my string variable to store the information in this format therefore
like my string variable mv should have some strings in first line and some
strings on second line and this whole should work like a single string
What is a string (std::string) in C++?
It is a container for a dynamically resizable array of characters, equipped
with methods for manipulating that array.
An array of characters is:
characters: |c0|c1|c2|c3|...|cN|
That's the nature of an std::string. There's nothing you can do about that.
What is a line (of text)?
There is no formal definition of a line in C++, or any other programming
language. A line is a visual concept that belongs to reading and writing
text arranged in 2-dimensional space. One line is vertically above or below
another.
Computers don't arrange data in 2-dimensional space. They arrange it all in
linear, 1-dimensional, storage. No data is vertically above or below any other data.
But of course programming languages can represent lines of text and they
all do it by the same convention. Conventionally, a line is an array of
characters that ends with a new-line sequence.
A new-line sequence is itself an array of one or two characters, depending
on your operating system's convention. Windows uses the 2-character sequence
carriage-return,line-feed. Unix-like operating systems use the 1-character
sequence line-feed. You can study the subject in
Wikipedia: Newline. But for
portability, in C++ source code the newline sequence - whatever it actually is -
is represented by the escape sequence
\n, which you can use in source code as if it were a character.
So the array of characters:
|h|e|l|l|o|\n|
represents the line of text:
hello
in C++. And the array of characters:
|h|e|l|l|o|\n|n|e|w|\n|w|o|r|l|d|\n|
represents the three lines of text:
hello
new
world
And if you want to store that array in a single std::string, C++ lets you do it
like this:
std::string s0{'h','e','l','l','o','\n','n','e','w','\n','w','o','r','l','d','\n'};
or more conveniently like this:
std::string s1{"hello\nnew\nworld\n"};
or even - if you have a phobia about using the \n escape sequence - like this:
std::string s2
{R"(hello
new
world
)"};
All of these ways of storing the three lines in a string create exactly the
same character array in that string, namely:
|h|e|l|l|o|\n|n|e|w|\n|w|o|r|l|d|\n|
They all create exactly the same std::string.
And if you print any of those strings you will see the same thing, e.g.
this program:
#include <string>
#include <iostream>
int main() {
std::string s0{'h','e','l','l','o','\n','n','e','w','\n','w','o','r','l','d','\n'};
std::string s1{"hello\nnew\nworld\n"};
std::string s2 // Yes...
{R"(hello
new
world
)"}; // ...it is meant to be formatted like this
std::cout << "--------------" << std::endl;
std::cout << s0;
std::cout << "--------------" << std::endl;
std::cout << s1;
std::cout << "--------------" << std::endl;
std::cout << s2;
std::cout << "--------------" << std::endl;
return 0;
}
outputs:
--------------
hello
new
world
--------------
hello
new
world
--------------
hello
new
world
--------------
Live demo

If I haven't understood your question wrong.
Here is your answer, add an escape character at the end of each line.
string mv = "hello\n\
new\n\
world\n";
\n -> new line
\ -> escape character
Here is the working example:
Example
string mv = "hello\n\
new\n\
world\n";

You can just add the \n character to the string to create a new line.
cout << "Hello \n New \n World" << endl;
This will output:
Hello
New
World

Related

How do I convert strings of numbers, coming from a .txt file into an int array using stoi::("string")

I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"
int main()
{
std::fstream Auftraege;
Auftraege.open("Auftraege37.txt", std::ios::out);
Auftraege << "10" << std::endl;
Auftraege << "1" << std::endl;
Auftraege << "20" << std::endl;
Auftraege.close();
int i = 0;
int auftraegearray[4];
std::string MengeanAuftraegen;
Auftraege.open("Auftraege37.txt", std::ios::in);
while (!Auftraege.eof())
{
getline(Auftraege, MengeanAuftraegen);
std::cout << MengeanAuftraegen << std::endl;
auftraegearray[i++] = std::stoi(MengeanAuftraegen);
}
Auftraege.close();

C++ cout or wcout a string contain "\n" isn't split the lines

C++11 and compiler is TDM-GCC.
I made an ini file and read string from it(UCS-2 LE BOM), by WinAPI,
GetPrivateProfileStringW.
[String]
Example = Today\nYesterday\nApple
My function library will return a variable, std::wstring. And it looks fine.
Then use wcout, just like:
#include <iostream>
#include <string>
using namespace std;
wstring readString = GetPrivateProfileStringW(); // Hide the details.
wcout << readString << endl;
And what do I get on my screen:
Today\nYesterday\nApple
What I want:
Today
Yesterday
Apple
I'm not sure why the "\n" is not work on this situation.
To avoid it, I can create multiple INI key and cout them using "endl".
But in this project, how many lines around here should be dynamic.
How do I cout the single string variable from Windows API on screen, become multiple lines?
The sequence \n is only recognized by the compiler in source code as part of a literal string or character. It's nothing that is built into the library or any standard functions.
If you want the sequence to represent a newline inside input you have read from an external source, you have to handle it yourself.

strlen not counting newlines?

I embedded lua into my project and came across a strange (for me) behavior of strlen and lua interpreting. I was trying to load a string, containing lua code, with luaL_loadbuffer and it consistently threw error of "unexpected symbol" on whatever was the last line of the lua code, except if the whole chunk was written in one line. so for example:
function start()
print("start")
end
would always results error: unexpected symbol on 3rd line, but
function start() print("start") end
loads successfully.
I figured out that loading the same chunk with luaL_loadstring, gives no errors, and saw that it uses strlen to determine the length of the specified string (I used std::string::size) and also that using strlen to provide the length of the string to the luaL_loadbuffer also results in successful loading.
Now the question was: what may be the difference between strlen and std::string::size, and at my most surprise the answer is that strlen is not counting new lines ('\n'). That is:
const char* str = "this is a string\nthis is a newline";
std::string str2(str);
str2.size(); // gives 34
strlen(str); // gives 33
The difference between the size, and the value returned by strlen was always the number of new line characters.
My questions are:
Does strlen really not counting newlines or I am missing something?
How do newlines affect the interpretation of the lua code internally?
I am using vs 2015 and lua 5.3.0
EDIT:
My first example was not exact, and did not produce the detailed effect for me neither, but I was able to recreate the problem from the original code:
std::fstream _Stream("test.lua", std::ios::ate | std::ios::in);
std::string _Source;
if(_Stream.is_open()) {
_Source.resize(_Stream.tellg());
_Stream.seekg(0, std::ios::beg);
_Stream.read(&_Source[0], _Source.size());
_Stream.close();
}
std::cout << "std::string::size() = " << _Source.size() << std::endl;
std::cout << "strlen() = " << strlen(_Source.c_str()) << std::endl;
The content of test.lua is "function start()\n\tprint("start")\nend\n\nstart()"
The difference is the number of newlines:
http://i.stack.imgur.com/y0QOW.png
Window's line endings (CR+LF) are two characters making the file size larger than the number of characters in the string so the resize operation uses the file size and not the length of the null-terminated string. strlen reports the length of the null-terminated string and counts \n as a single character. You can make the size match the length of the C string by resizing the string to match afterwards:
_Source.resize(strlen(_Source.c_str()) + 1);

How to round a number to the nearest hundreath and make that display on a string in c++

I am working on a money program. Currently I am trying to make a part in the program that displays a list that shows every transaction that was made in the session. My problem is that when I convert the money amount to a string instead of displaying something like 100.35 in when converted to a string it instead displays something like 100.35000000. I was wondering if there was any way I could make the program drop the additional zeros? Here is a sample of how I convert the numbers to a string
int main(){
double samplemoney=100.35;
string sample="Today we made $";
string comsample;
comsample=sample+std::tostring(money)+".";
cout<<comsample<<endl;
return 0;
}
In my main program this part is handled with a class but as I said earlier it seems like no matter what the money value I put in is it will display a series of zero and I want my program to drop the unnecessary zeros.
Let's say you have this number:
double number = 190.0391000;
If the problem is displaying the value you may use
std::cout << std::setprecision(5) << number
where f is the number you want to show.
If your problem is having a string with a finite precision you can use sprintf() in the following way:
char arr[128];
sprintf(arr,"%3.2f", number);
std::string formattedstring(arr);
or in a more C++ oriented way something like this
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
and then you get the string in the following way:
std::string formattedstring = strn.str();
I attach the full text of program here... tested on my machine:
#include <sstream>
#include <iostream>
int main() {
float number=100.24324232;
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
std::cout << strn.str() << "\n";
return( 0 );
}

c++ c_str adding strange characters to the end of the string

let me first thank you for taking the time to read this.
I'm trying to read a file in c++. Currently I have a method that allows the user to select a file in explorer and returns this as an 'std::string'. I then have to open this file, but the method I have for this uses const char*. Therefore I need to convert from one to the other.
If there is an easy method in windows for reading a file using a string instead then let me know as it would solve my entire problem.
When I convert from string to const char*, using str.c_str(), I get a lot of weird characters at the end. I've researched other topics with the same problem, but the answers all seem very specific for those projects, or say just stick to sting/vector instead. Obviously I would happily do this, but I don't have a method that opens the file using a string/vector.
Any help is appreciated :) The code and output of where this occurs is pasted below.
*SOURCE
std::string f;
if (LOWORD(wParam) == 1) {
f = openFile();
char *fchar = new char[f.size()+1]; // +1 to account for \0 byte
//char *fchar = std::vector[1];
std::strncpy(fchar, f.c_str(), f.size());
file1 = fchar;
std::cout<<"string size: " << f.size() << std::endl;
std::cout<<"string: " << f << std::endl;
std::cout<<"fchar: " << fchar << std::endl;
std::cout<<"file1: " << file1 << std::endl;
}
OUTPUT
string size: 33
string: C:\Users\Joseph\Pictures\back_raw
fchar: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■
file1: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■**
std::strncpy() does not place a `\0' character at the end of the string. See http://www.cplusplus.com/reference/clibrary/cstring/strncpy/. You need to copy that as well:
std::strncpy(fchar, f.c_str(), f.size() + 1);
Where is file1 declared ?
What about openFile ? (would like to know its return type)
Could you try to manually put that '\0' ? IMHO, your char* is simply lacking the \0 at the end...
Make sure you put a \0 at the end, everywhere you need to.

Resources