\n not working after I hit the enter button [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I am writing a cout statement in C++, but the statement is very big so I pressed enter so that I can start from next line (not want to write full long statement in one line). It was working fine but if \n (new line) is the first character after hitting the enter as you can see the second line of code it was not working. So I just want to ask is there any way to start your code from the next line (continuing the previous line of code) after hitting enter.
cout<<"\nChoose the operation you want to perform :
\n1. To insert a node in the BST and in the tree \n2";

Yes, you can this way:
std::cout << "\nChoose the operation you want to perform:\n"
"1. To insert a node in the BST and in the tree\n"
"2. ...\n";
You cannot have a string on one line that doesn't end with a ", but two properly terminated strings in a row are concatenated. So "foo" "bar" becomes "foobar". Having "foo" and "bar" on separate lines is fine.
As others have mentioned, C++11 supports raw string literals, which do allow strings to be spread out over multiple lines, and avoids having to write \n:
std::cout << R"(
Choose the operation you want to perform:
1. To insert a node in the BST and in the tree
2. ...
)";

You can either use a multiline string literal like
const char* s1 = "\nChoose the operation you want to perform:\n"
"1. To insert a node in the BST and in the tree\n"
"2. some text here";
our you can use raw string literals without any quotes or new line literals (cf, for example, string literals at cppreference.com):
const char* s1 = R"foo(
Choose the operation you want to perform:
1. To insert a node in the BST and in the tree
2. some text here)foo";
These two s1-variants are equivalent. Then write
std::cout << s1;

You have the option:
std::cout << "\nSome text,\n"
"\nsomething else\n";
(which was originally proposed by #G. Sliepen)
I would rather prefer using std::endl.
The code would look like:
std::cout << std::endl << "Some text," << std::endl <<
std::endl << "something else" << std::endl;
Yet another option is to use R prefix (which is used to avoid escaping of any character):
std::cout << R"(
Some text,
something else
)";
My favourite is the last one.

Related

What is the simplest way to remove the empty characters at the start of a string in C++? [duplicate]

This question already has answers here:
Removing leading and trailing spaces from a string
(26 answers)
Closed 2 years ago.
I'm a student so sorry if this is too basic of a question. I want to remove the whitespace at the start of a string, without removing the space between words.
stringstream parser(oneLine) ;
double amount ;
parser >> amount ;
string desc ;
getline(parser, desc) ;
cout << "Amount: $" << amount << " Desc: " << desc << endl ;
For example, I have this function I'm working on. It will read lines in from a text file, which are in the format of ex "10 Streaming Subscription."
The variables are currently: Amount = "10", desc =" Streaming Subscription" but I want desc to be "Streaming Subscription."
You can do it with a search and an erase:
const std::size_t pos = desc.find_first_not_of(' ');
if (pos != std::string::npos)
desc.erase(0, pos);
I wouldn't, though; erasing from the start of a string is not super-trivial, and you don't really need to do it.
I'd put parser.ignore(std::numeric_limits<std::streamsize>::max(), ' ') before your getline call instead, so the spaces never get read in the first place.
Note that if your input file is not formatted as you've described, this line will just keep looking for a space and chucking everything away until it finds one: if you think you may need to be more flexible, it's time to std::getline the whole line in the first place then parse it to an amount and a description after-the-fact.
Note that both solutions only consider space (U+0020) characters; you can expand it to care about e.g. tabspaces if you like. This is easy for the first approach, and slightly more complex for the second approach; in either case, I'll leave it as an exercise to the reader.

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.

Taking data from columns in two separate files and combining in another file

There are two files, each has multiple columns of data, up to around 14,000 rows, neatly spaced and everything. File1 has 6 columns (Student ID #, semester code #, class name, class code # (though some have letters), the letter grade the student received, and the numeric grade they received.
The second file has 4 columns. Class name, class code, how many hours per week it is, and designation code (three letters indicating whether its a liberal arts class or not).
The task is to output everything from the first file into the new file, but add on two columns (from the second file) corresponding to each appropriate row, that have the hours for the course and designation code.
The second task is to take this new file, and output into it the students ID, overall GPA, GPA in CSCI courses, and a percent of hours spent taking non-liberal arts courses.
I'm not asking for someone to do it for me (obviously), it's just that I've run out of ideas. We're supposed to use nothing more than fstream, iostream, strings, if statements, loops, functions, and " .clear(); " and " seekg(ios::beg); " (also we're not supposed to use getline)
basically super simple stuff, no arrays or vectors or anything.
I figured out how to output parts of the two files into the third file using while loops and if statements, but I have no idea how to tell it to compare values in a column from one file to a column in a different file and that if the values are equal, to output the corresponding values from the other columns (the amount of hours for each class and designation code). And I need a lot of help with the second task as well.
What you're looking for is a map. If you need help streaming into a map you can check out this post: Is there a Way to Stream in a Map?
But what you'll want to do is stream File2 into a map, useing the "class code" as the map key, and a tuple or your own custom struct as value. Then index that map with the "class code #" from the line you're currently outputting from File1, appending the appropriate elements of the map's indexed value.
All this may sound like hand-waving, so, because the question lacks an exemplary input and output, I have created an exemplary File1 input as though it had already been streamed in: tuple<int, int, string, string, char, int> File1[] = {make_tuple(13, 1, "Computer Science 1", "CS101", 'A', 100), make_tuple(13, 2, "Computer Science 2", "CS201", 'A', 100)}; and File2 input as though it had already been streamed in: map<string, tuple<string, int, string>> File2 = {make_pair("CS101", make_tuple("Computer Science 1", 4, "NOT")), make_pair("CS201", make_tuple("Computer Science 2", 4, "NOT"))};
These can then be streamed out, potentially to another file as follows:
for(auto& it : File1) {
const auto& i = File2[get<3>(it)];
cout << get<0>(it) << ' ' << get<1>(it) << ' ' << get<2>(it) << ' ' << get<3>(it) << ' ' << get<4>(it) << ' ' << get<5>(it) << ' ' << get<1>(i) << ' ' << get<2>(i) << endl;
}
[Live Example]

Is this regular expression?

This is how to split string in Unityscript from Unity Wiki. However, I don't recognize " "[0]. Is this regular expression? If so, any reference to it? I'm familiar with regular expressions generally and used them a lot, but this syntax is little confusing.
var qualifiedName = "System.Integer myInt";
var name = qualifiedName.Split(" "[0]);
Wiki Reference
On any string, wether it is a variable or a literal (" "), you can use an indexer to get the char at the nth position.
Your codesample is a very weird way of literally defining a char with a space, and could be simplified by using this:
' '
note the single quotes instead of double quotes
As many have already mentioned, " "[0] is the first character of the " " string (which is a System.String, or an array of System.Chars. The problem with UnityScript is that ' ' is interpreted as a String too, so the only way to provide a Char is by slicing.
" "[0] is the first character of the string " ".
typeof " "[0]; // "string"
Your example is strange, because " "[0] and " " are strictly equal.
" "[0] === " "; // true
Reading reference:
Mono Types When a Mono function requires a char as an input, you can
obtain one by simply indexing a string. E.g. if you wanted to pass the
lowercase a as a char, you'd write: "a"[0]
I suppose it's because UnityScript is implemented in Boo and String is provided by mono.

How to declare a variable that spans multiple lines

I'm attempting to initialise a string variable in C++, and the value is so long that it's going to exceed the 80 character per line limit I'm working to, so I'd like to split it to the next line, but I'm not sure how to do that.
I know that when splitting the contents of a stream across multiple lines, the syntax goes like
cout << "This is a string"
<< "This is another string";
Is there an equivalent for variable assignment, or do I have to declare multiple variables and concatenate them?
Edit: I misspoke when I wrote the initial question. When I say 'next line', I'm just meaning the next line of the script. When it is printed upon execution, I would like it to be on the same line.
You can simply break the line like this:
string longText("This is a "
"very very very "
"long text");
In the C family, whitespaces are insignificant, so you can freely use character literals spanning multiple lines this way.
It can also simply be
cout << "This is a string"
"This is another string";
You can write this:
const char * str = "First phrase, "
"Second phrase, "
"Third phrase";