When output to the console, a "%" symbol is added in linux. C++ - c++

I use Manjaro Linux, DISTRIB_RELEASE=22.0.0, GNOME 43.1, Kernel 5.19.17-2, and I used zsh.
I decided to learn C++, but I ran into a problem. If I didn't add std::endl when outputting to the console, the symbol "%" is added.
See the screenshots attached.
Code1:
#include <iostream>
int main()
{
int age;
age = 28;
std::cout << "Age = " << age;
return 0;
}
Code2:
#include <iostream>
int main()
{
int age;
age = 28;
std::cout << "Age = " << age << std::endl;
return 0;
}
Why is this happening? All I tried was just adding std::endl. I want to know why the "%" symbol is being added.

Ah, you're omitting the final line break.
Your shell hence should (would it be very true to what your program actually produced in output) display the prompt on the same line as your output.
Now, that would look terrible and be confusing. So, instead your shell inserts a special character with a special background color to mark "hey, this isn't the program's output, but I'm still inserting a line break here, because I don't hate you, dear user".
That percentage symbol is not from your program. It's your shell trying to be sensible.

From the man page for zsh:
When a partial line is preserved, by default you will see an inverse+bold character at the end of the partial line: a % for a normal user or a # for root. If set, the shell parameter PROMPT_EOL_MARK can be used to customize how the end of partial lines are shown.

Related

Is it possible to print this shape without printing spaces in C++ as described in the book "Think Like Programmer" by Anton Spraul?

In a book named "Think Like a Programmer" by Anton Spraul, on chapter 2, exercise 1, page 53, this is what is written:
Using the same rule as the shapes programs from earlier in the chapter
(only two output statements — one that outputs the hash mark and one
that outputs an end-of-line), write a program that produces the
following shape:
########
######
####
##
So we can only use cout << "\n"; and cout << "#"; but not cout << " ";
Solving this problem by printing spaces is easy (see code below). But is it possible to print such shape without printing spaces in C++?
#include <iostream>
using std::cin;
using std::cout;
int main()
{
int shapeWidth = 8;
for (int row = 0; row < 4; row++) {
for(int spaceNum = 0; spaceNum < row; spaceNum++) {
cout << " ";
}
for(int hashNum = 0; hashNum < shapeWidth-2*row; hashNum++) {
cout << "#";
}
cout << "\n";
}
}
Solving this problem by printing spaces is easy (see code above). But is it possible to print such shape without printing spaces in C++?
In one of the answers I read one can remove the for (int spaceNum. . . loop and rather just put cout << setw(row+1); to achieve that.
Clarification: The author never used a shape as example where one had to print spaces or indentations like the above. Interpreting the exercise above literally, he expects us to write that shape by printing "#" and "\n" only. Printing spaces or indentations by only printing "#" and "\n" seems not possible to me, so I thought maybe he was not careful when he wrote exercises. Or there's a way to achieve that but it's just me who doesn't know. This is why I asked this.
Yes, this is possible.
Set the stream width to the length of the row.
Set the stream formatting to right-justified.
Look up stream manipulators in your book or another C++ references.
Possibly! But that is a question about the system you’re running on, not about C++. As far as the language is concerned, it’s just outputting characters. The fact that outputting a “space” character moves the cursor to the right on the screen — or even the existence of the screen — is a matter of how the operating system and the software running on it interpret the characters that have been output.
Most notably, you can use ANSI escape sequences to move the cursor around on most text consoles. There’s no particular reason to do this unless you’re writing a full-screen text mode UI.

Console has input prompt then closes without output on a very simple program

I have a very simple program that won't give any console output.
I've tried getting input at the end using cin.get() and holding with system("pause"). I've also tried getting input at the start of the program then outputting at the end.
#include <iostream>
using namespace std;
int main(){
int bulb, bulbOpen=0, multiple;
for ( bulb=1; bulb<101 ; bulb=bulb+1 ){
for ( multiple=1; 100; multiple++){
if (bulb/multiple==0){
bulb = bulb * (-1);
}
}
if ( bulb<<0 ){
bulbOpen = bulbOpen + 1;
}
}
cout << "The remaining open light bulbs are " << bulbOpen << "." << endl;
return 0;
}
I'm a beginner programmer so any help, recommendations and explanations are very welcome.
EDIT:
Thanks to Rapha for the fixes and the advice, here's the updated code:
#include <iostream>
int main(){
int bulb, bulbCopy, bulbOpen=0, multiple;
for ( bulb=1; bulb<101 ; bulb++ ){
bulbCopy = bulb;
for ( multiple=1; multiple<101; multiple++){
if (bulbCopy%multiple==0){
bulbCopy = bulbCopy * (-1);
}
}
if ( bulbCopy<0 ){
bulbOpen = bulbOpen + 1;
}
}
std::cout << "The remaining open light bulbs are " << bulbOpen << "." << std::endl;
std::cin.get();
return 0;
}
The exercise went like this: You've got 100 light bulbs. You take every number from 1-100 and for every lightbulb with the position a multiple of said number, you switch it's current state. So basically if you've got bulb 2, you first switch it ON because it's a multiple of 1, then you switch it OFF because it's a multiple of 2.
And you've got to check how many remaining lightbulbs are still open by the end.
The answer is 10.
The Main-Problem why you get no output is, that the code is causing an infinity-loop (The loop cant escape and will run forever) and you never reach the std::cout part of the code
Ok there's a lot going on and the first thing is (You probably will hear this a lot on this platform) don't use using namespace std; instead use the std::-prefix for c++-Standard Things. I think its ok to use if you start out, but its a really bad Practice.
Then another thing is, cin.get() already 'pauses' or interrupting the program until you entered an input so system("pause") really isn't needed here.
To get input simply do it like that:
int input;
std::cin >> input;
std::cout << "My output was: " << input;
Then another thing is, i dont really know what you try to do with the nested for-loops but in the second for-loop you have a conditions that doesnt really make sense
for(multiple=1; 100; multiple++)
^^^
What you probably want is something like
for(multiple=1; multiple<100; multiple++)
And then saying bulb/multiple==0 doesn't really make sense either, because its only true if bulb is 0, maybe you mean bulb%multiple==0 (modulo).
And there's probably a typo in one condition where you wrote bulb<<0 where you probably want to write bulb<0
But no matter what you do, it still runs into a infinite loop, because the conditions are weird. And in normal cases you really shouldn't change the iteration-variable of your loop inside your loop (only if you know thats exactly what you want) but in most cases that just breaks your program, especially if youre starting to learn the language.
Maybe if you say exactly what you want, we can help you more.

Output when a user enters string for an int variable

I'm currently reading Stroustrup's book on C++. In the user input section, it has the following example -
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "Please enter your first name and age:\n";
string firstName = "???"; // "??? means don't know the name"
int age = -1; // -1 means don't know the age
cin >> firstName >> age;
cout << "Hello " << firstName << " (age " << age << ")\n";
}
As per the book, we initialize the age variable so as to get a predictable value if the input fails.
The example says that the input 22 Carlos will produce an output of Hello 22 (age -1).
I've typed in the same code in a text editor (Sublime Text), but when I run the code with the above input, I get an age of 0 (not -1).
Here's the screenshot of the outputs I get -
output image from terminal.
And, here's the version of the compiler that I'm using -
compiler-version.
Can anyone explain as to why I don't get -1 as the age output, as the book claims?
The short answer is that both are correct if that version of the book is more than a few years old.
Prior to C++11, the default behaviour of operator>> extracting an integer was to leave it unchanged if the extraction fails.
In C++11, this behaviour was changed to store 0 into the integer when extraction fails.
I don't have knowledge of why the change was made, but my guess is that it prevents a common class of undefined behaviour from people leaving a variable uninitialized and then not checking that extraction succeeded before using the variable.
Unfortunately, the machinery behind formatted input is quite lengthy, but the condensed version is that the call ultimately boils down to num_get::get(), where this behaviour is specified.1
1: For your interest, it's also possible to attach a different facet for formatted input to use instead, meaning you could specify whatever behaviour you want for failure.

In C/C++, how do you edit a certain 'coordinate' in stdout?

I've been using Vim a lot lately, and I was wondering how the program manages to change the characters at certain positions in the terminal. For example, when using :rc, it replaces the character under the cursor with c.
I have also seen similar things done with Homebrew, which prints a progress bar to the screen and updates it when necessary.
How is this done in C/C++?
There is no standard way of doing this in C++.
It is done with OS dependent lbiraries, such as curses and similar libraries (ncurses) in the Unix/Linux world. Some of these libraries have been ported on across platforms (example: PDCurses)
For very simple things such as a progress bar or a counter, and as long as you remain on a single line there is the trick of using "\r" (carriage return) in the output, to place the cursor back at the begin of the current line. Example:
for (int i = 0; i < 100; i++) {
cout << "\rProgress: " << setw(3) << i;
this_thread::sleep_for(chrono::milliseconds(100));
}
Certainly, using ncurses or similar library is a good answer. An alternative may be to use ANSI Escape Codes to control the cursor in some terminal emulators (but not Windows command shell). For example, this code prints a line in multiple colors and then moves the cursor to 2,2 (coordinates are 1-based with 1,1 being the upper left corner) and prints the word "red" in the color red.
#include <iostream>
#include <string>
const std::string CSI{"\x1b["};
const std::string BLUE{CSI + "34m"};
const std::string RED{CSI + "31m"};
const std::string RESET{CSI + "0m"};
std::ostream &curpos(int row, int col)
{
return std::cout << CSI << row << ';' << col << 'H';
}
int main()
{
std::cout << "This is " << BLUE << "blue" << RESET << " and white.\n";
curpos(2,2);
std::cout << RED << "red" << RESET << '\n';
}
As mentioned that's not a matter of any C/C++ standard operations provided with stdout or cout (besides writing the necessary control characters to the screen).
Controlling the screen cursor of an ASCII terminal totally depends on implementation of the particular terminal program used, and besides a very narrow set of control characters, there's no standard established.
There are libraries like ncurses for a broader variety of linux terminal implementations, or PDcurses for a windows CMD shell.
I'm not sure to understand you completely but with creating an array of 100 elements of type char you can modify any position of the array and loop it with a std:cout to mostrate it on the console.
Perhaps could be better define the array of 50 chars to resuce the size of the printed result.
For example, if you have to print a progessbar in the 1% process, you should print:
Char progressbar[100] = {'X','','','','','','','','',........}

sstream not working...(STILL)

I am trying to get a double to be a string through stringstream, but it is not working.
std::string MatlabPlotter::getTimeVector( unsigned int xvector_size, double ts ){
std::string tv;
ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
It outputs only "0:" on my console...
I'm working on two projects, both with the same problem. I'm posting a different one, which runs into the same problem. It is posted here:
http://pastebin.com/m2dd76a63
I have three classes PolyClass.h and .cpp, and the main. The function with the problem is PrintPoly. Can someone help me out? Thanks a bunch!!
You're printing correctly, however your logic in the order of printing is incorrect.
I modified it to work they way I think you wanted it to, let me know if this helps.
http://pastebin.com/d3e6e8263
Old answer:
Your code works, though ostringstream is in the std namespace. The problem is in your file printing code.
Can I see your call to the function?
I made a test case:
// #include necessary headers
int main(void)
{
std::string s;
s = MatlabPlotter::getTimeVector(1,1.0);
}
The output I get is 0:1:1
The following code is 100% correct:
#include <iostream>
#include <sstream>
#include <string>
// removed MatlabPlotter namespace, should have no effect
std::string getTimeVector(unsigned int xvector_size, double ts)
{
// std::string tv; // not needed
std::ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
int main(void)
{
// all work
// 1:
getTimeVector(0, 3.1415);
// 2: (note, prints twice, once in the function, once outside)
std::cout << getTimeVector(0, 3.1415) << std::endl;
// 3: (note, prints twice, once in the function, once outside)
std::string r = getTimeVector(0, 3.1415);
std::cout << r << std::endl;
}
Find where we differ, that's likely your source of error. Because it stops at your double, I'm guessing the double you're trying to print is infinity, NaN (not a number), or some other error state.
I can't really help with the "no output" part of this, as you didn't show your code that tries to output this. As a guess, did you perhaps not put an EOL in there somehow? Some systems won't give any text output until they hit a newline. You can do this by tacking a << std::endl onto your line, or a '\n' to your string.
Since you didn't put down a using for it, you need to use the type std::ostringstream. This is similar to how you had to use "std:string" instead of just "string".
Also, were it me, I'd get rid of that temp variable and just return ss.str(); It is less code (to possibly get wrong), and probabaly less work for the program.
Well, I tried the code you linked to and it outputs
B 4
A 5
B 4
C 3
x^ + 5x^ + 3
for me before crashing although the crash happens after PrintPoly. From looking at the code this is what I'd expect it to print. Are you saying you get no integers appearing after the letters?
Thanks all for your input! Not sure of the exact error, but it must be some setting in XCode which is messing it up. I made a CMakeLists.txt file and compiled it from the terminal using
cmake -G XCode ..
and produced an XCode project. I ran it, and now it works fine...now would anyone happen to know what might cause XCode to do this? I'm running version 3.2 with the following:
64-bit
Component versions
Xcode IDE: 1610.0
Xcode Core: 1608.0
ToolSupport: 1591.0