I'm trying to create a linux man page for my program. I'm using getopt to parse several command line arguments and flags, one of which may be 'h', which should print the man page then exit.
I'm programming in VS 2013, and this nagging little error won't go away. According to intellisense, a semicolon is expected on the line that says "-c, --container\n". From my understanding of multi-line string literals, you only place a semicolon after the body of text you want to put inside a std::string, which is why this is particularly frustrating.
Below is my code:
case 'h':{
string out;
out = "NAME\n"
"\tblah.\n"
"SYNOPSIS\n"
"\tmore text\n"
"\tprogram (-h | --help)"
"DESCRIPTION\n"
"\ttext text text\n"
"\tAI. mpre text\n"
"\ttext\n"
"\ttext.\n"
"OPTIONS\n"
"-h, --help\n"
"\tPrint this help screen and exit.\n"
"-c, --container\n"
"\ttext\n"
"\ttext\n"
"text\n"
"\ttext.\n"
"-v, --verbose N\n"
"\tdescriptions\n"
"\tstatistics.\n"
"-d, --debug\n"
"\ttext\n";
ss << out;
cout << ss.str();
cout.flush();
exit(0);
break;
}
How can I fix this particularly annoying error? Thanks in advance.
When I copy-and-paste your source code, I get some odd non-printable characters, including some on the "-c, --container\n" line. They appear to be UTF-8 encoded SOFT HYPHEN characters (the UTF-8 encoding may be an artifact of how you copy-and-pasted the code into your web browser). Filter those out and you should be ok.
Related
I add a break point in Visual Studio 2015, with an action to output a string to Output Window. There will be an auto-added line break at the end. Problem is, my previous output message(which is not output by break point) has no line break.
So I want to add new line character at the beginning of my string, to avoid it messing up with my previous message. I tried to add \n, but the \n outputs as it is, without being escaped.
How to add a new line character in break point's action?
Here are four things for you to try:
You can produce a line break using the debugger expression {"\n",s8b} which makes use of the C++ debugger format specifier s8b (unquoted 8-bit string).
Here's an example with a two-line message First{"\n",s8b}Second:
(Other than that, I am not aware of any other way to include line breaks in the message. While there are ways to enter a multi-line message (by entering line break characters' Unicode code points using the numpad), Visual Studio will just throw away everything but the first text line entered.)
Just before your current breakpoint, add an additional breakpoint with a very short action message (a dot or comma) in order to get an additional line break before your real message.
If you're on Windows (which appears likely, given Visual Studio), you can send a message to the debugger using the Windows API function OutputDebugString. This is the currently suggested solution to the SO question, "How do I print to the debug output window in a Win32 app?"
Write a message to clog: std::clog << message << std::endl;.
In Addition to the answer from stakx that matches the original question for debugging C++ applications, I would like to add a character sequence that instead works for debugging .NET applications:
{"\n",nq}
The C++ sequence would otherwise result in this error message: 's8b' is not a valid format specifier
I'm working on a c++ console project and i would like to show a percentage without making a new line each time (so that the window doesn't get clogged with thousands of lines).
Is there a way of removing the last line that was printed or something to say that the next time that i output a line it should replace the current line?
You can use a \r (carriage return) to return the cursor to the beginning of the line:
This works on windows and Linux.
From: Erase the current printed console line
You could alternatively use a series of backspaces.
string str="Hello!";
cout << str;
cout << string(str.length(),'\b');
cout << "Hello again!";
From: http://www.cplusplus.com/forum/unices/25744/
Maybe mark as duplicate? I am really not sure how.
A simple example that I tested on Linux would be:
std::cout << "Some text to display..." << "\t\r" << std::flush;
Here the \t adds a tabulation to handle slightly varying string lengths and \r sends the cursor back at the start of the line (as mentioned in other answers).
std::flush is required to guarantee that the line is displayed without jumping to the next line.
This is very platform-dependent and terminal-dependent. But, you may want to look at ncurses for a start: http://linux.die.net/man/3/ncurses
For Windows: How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?
For Linux: https://unix.stackexchange.com/questions/43075/how-to-change-the-contents-of-a-line-on-the-terminal-as-opposed-to-writing-a-new
I'm trying to run a .exe that requires some parameters by using system().
If there's a space in the .exe's path AND in the path of a file passed in parameters, I get the following error:
The filename, directory name, or volume label syntax is incorrect.
Here is the code that generates that error:
#include <stdlib.h>
#include <conio.h>
int main (){
system("\"C:\\Users\\Adam\\Desktop\\pdftotext\" -layout \"C:\\Users\\Adam\\Desktop\\week 4.pdf\"");
_getch();
}
If the "pdftotext"'s path doesn't use quotation marks (I need them because sometimes the directory will have spaces), everything works fine. Also, if I put what's in "system()" in a string and output it and I copy it in an actual command window, it works.
I thought that maybe I could chain some commands using something like this:
cd C:\Users\Adam\Desktop;
pdftotext -layout "week 4.pdf"
So I would already be in the correct directory, but I don't know how to use multiple commands in the same system() function.
Can anyone tell me why my command doesn't work or if the second way I thought about would work?
Edit: Looks like I needed an extra set of quotation marks because system() passes its arguments to cmd /k, so it needs to be in quotations. I found it here:
C++: How to make a my program open a .exe with optional args
so I'll vote to close as duplicate since the questions are pretty close even though we weren't getting the same error message, thanks!
system() runs command as cmd /C command. And here's citation from cmd doc:
If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- no /S switch
- exactly two quote characters
- no special characters between the two quote characters,
where special is one of: &<>()#^|
- there are one or more whitespace characters between the
two quote characters
- the string between the two quote characters is the name
of an executable file.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
It seems that you are hitting case 2, and cmd thinks that the whole string C:\Users\Adam\Desktop\pdftotext" -layout "C:\Users\Adam\Desktop\week 4.pdf (i.e. without the first and the last quote) is the name of executable.
So the solution would be to wrap the whole command in extra quotes:
//system("\"D:\\test\" nospaces \"text with spaces\"");//gives same error as you're getting
system("\"\"D:\\test\" nospaces \"text with spaces\"\""); //ok, works
And this is very weird. I think it's also a good idea to add /S just to make sure it will always parse the string by the case 2:
system("cmd /S /C \"\"D:\\test\" nospaces \"text with spaces\"\""); //also works
I got here looking for an answer, and this is the code that I came up with (and I was this explicit for the benefit of next person maintaining my code):
std::stringstream ss;
std::string pathOfCommand;
std::string pathOfInputFile;
// some code to set values for paths
ss << "\""; // command opening quote
ss << "\"" << pathOfCommand << "\" "; // Quoted binary (could have spaces)
ss << "\"" << pathOfInputFile << "\""; // Quoted input (could have spaces)
ss << "\""; // command closing quote
system( ss.str().c_str() ); // Execute the command
and it solved all of my problems.
Good learning from here on the internals of System call.Same issue reproducible(of course) with C++ string, TCHARs etc.
One approach that always helped me is SetCurrentDirectory() call. I first set current path and then execute. This has worked for me so far. Any comments welcome.
-Sreejith. D. Menon
I have C code like this:
#include<stdio.h>
int main()
{
printf("Hey this is my first hello world \r");
return 0;
}
I have used the \r escape sequence as an experiment. When I run the code I get the output as:
o world
Why is that, and what is the use of \r exactly?
If I run the same code in an online compiler I get the output as:
Hey this is my first hello world
Why did the online compiler produce different output, ignoring the \r?
\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r allows to override the current line of the terminal emulator.
Tom Zych figured why the output of your program is o world while the \r is at the end of the line and you don't print anything after that:
When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world.
The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r has no effect.
See https://en.wikipedia.org/wiki/Carriage_return
Here is a usage example of \r:
#include <stdio.h>
#include <unistd.h>
int main()
{
char chars[] = {'-', '\\', '|', '/'};
unsigned int i;
for (i = 0; ; ++i) {
printf("%c\r", chars[i % sizeof(chars)]);
fflush(stdout);
usleep(200000);
}
return 0;
}
It repeatedly prints the characters - \ | / at the same position to give the illusion of a rotating | in the terminal.
The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.
The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.
Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.
Hope this helps!
PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.
\r move the cursor to the begin of the line.
Line breaks are managed differently on different systems. Some only use \n (line feed, e.g. Unix), some use (\r e.g. MacOS before OS X afaik) and some use \r\n (e.g. Windows afaik).
As amaud576875 said, the \r escape sequence signifies a carriage-return, similar to pressing the Enter key. However, I'm not sure how you get "o world"; you should (and I do) get "my first hello world" and then a new line. Depending on what operating system you're using (I'm using Mac) you might want to use a \n instead of a \r.
This is from antiquated technology: The old fashion typewriter style of printer. There was a roller (platen) that advanced the paper and a print head that hammered a metal key against an ink fabric.
\r Return the print head to the left side.
\n Advance the platen one line.
If the \n was not issued, you would type over what was on a line (used mostly for underlining text).
To answer the part of your question,
what is the use of \r?
Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:
fprintf(socket, "RCPT TO: %s\r\n", recipients);
Or, when a FTP server replies with a permission-denied error:
fprintf(client, "550 Permission denied\r\n");
It is quite useful, when you are running on the unix platform, and need to create a text file
which will be opened on the dos platform.
Unix uses '\n' as its line terminator, and dos uses '\r\n' as its line terminator, so you can use it to create a dos text file.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've been trying to learn C++ lately, and all has been going well until today. I'm trying to make a very simple application that basically just asks a user for a number and then displays the factorial of that number.
When I try to compile the file in Cygwin (g++ factorial.cpp -o fact), I get the following warning "warning: no newline at end of file". Following the words of the warning, I added a newline at the end of the file and tried it again...with the exact same result. Whether I try one newline or twenty, it never seems to compile.
I attached the simple, and still unfinished, file below (Except imagine there is a blank line at the end of it. This noob can't get it show up in code view):
#include <iostream>
#include <string>
using namespace std;
int getInput();
void displayFactorial(int);
int main()
{
int number = getInput();
displayFactorial(number);
return 0;
}
int getInput()
{
int userNumber;
bool okNumber;
while(okNumber == false){
cout << "Please eneter a number in the range of 1-10";
cin >> userNumber;
if(userNumber >= 1 and userNumber <=10){
okNumber = true;
}
else{
cout << "Incorrect number" << endl;
}
}
return userNumber;
}
void displayFactorial(int number){
string displayString = number + "! =";
int total;
for(int i = 0; i<=number; i++){
//displayString += "
}
cout << displayString;
}
// File ended the line above this (with a new line. This line added by Martin so it shows)
Any idea what could cause that warning if it's not the newline?
First of all a warning does not prevent a program from compiling.
Second: Are you sure you compile the file you are editing?
I held some tutorials at my university and most of the beginners made this mistake.
If you can definitely say you are compiling the file you are editing, then it could be caused by different new line settings but I consider this highly improbable.
Which editor/IDE do you use?
All you have to do is wait for the new C++0x standard. A newline is no longer required at the end of the source file. (And this took 40 years?)
Most Unix-based text editors will add a trailing newline automatically, but apparently
Notepad++ (which I've never used) doesn't.
The file doesn't need to end with a blank line (which would be represented as two newline
characters in a row), just a properly terminated one.
See if Notepad++ has a configuration option that tells it to automatically append a newline
when saving a file, or at least to ask whether you want to add one.
Great explanation - I had the same problem and solved it simply by using WordPad instead of Notepad :)
The problem has nothing to do with your C++ code; I can almost guarantee you that the uninitialized boolean in your program didn't cause the issue. It's a problem with the source file itself. A "Hello, world" program would have produced the same warning.
A text file, including a C++ source file, consists of lines of characters, where each line is terminated by an end-of-line marker. In Unix, and therefore in Cygwin (with the default settings), the end-of-line marker is a single '\n' (newline, linefeed) character. (Windows uses CR-LF pair ("\r\n").
It's possible for the very last line of a text file not to end with a newline character, but g++ prefers it to be terminated properly.
Most Unix-based text editors will add a trailing newline automatically, but apparently Notepad++ (which I've never used) doesn't.
The file doesn't need to end with a blank line (which would be represented as two newline characters in a row), just a properly terminated one.
See if Notepad++ has a configuration option that tells it to automatically append a newline when saving a file, or at least to ask whether you want to add one.
(The missing newline at the end of the file is probably what caused your problems pasting the code when you posted the question.)
Maybe it is some problem with some invisible character? I copy-paste your code and gets compiled without any warnings/errors, under Cygwin with the following g++:
$ g++ --version
g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
It ended up that not initializing a boolean variable to false was the issue. However, I'm not sure whether it was actually the initialization that was the problem, or just the fact that the text editor might not actually save a file if you just append whitespace to the end of it. For those wondering, this was happening to me in Notepad++.