formatting printf statement in cpp file - c++

I have a cpp file within an xcode application, but am having trouble formatting the printf correctly.
My code is:
b2Vec2 axisA = b2MulT(xfA.R, m_axis);
printf("axis A = XXX", axisA);
I need to know what to put in XXX to print out the value of the 'axisA' variable.
Thanks

Printf accepts only plain data types, so you need to break it down:
printf("axis A = (%f,%f)", axisA.x, axisA.y);
or
printf("axis A = (%g,%g", axisA.x, axisA.y);

Related

How do I use std::rename with variables?

In my program, I store data in different text files. The data belongs to an object, which I call rockets. For example, the rocket Saturn 5 has a text file labeled "Saturn5R.txt". I want an option to rename the rocket, and so I will need to rename the text file as well. I am using std::rename in the library. I have gotten it working with something like this:
char oldname[] = "Saturn5R.txt";
char newname[] = "Saturn6R.txt";
if (std::rename(oldname, newname) != 0) {
perror("Error renaming file");
}
This works, but I don't want to always be renaming Saturn5R.txt to Saturn6R.txt. What I want to do is to be able to rename any text file to any name, I have tried this and I get an error:
char oldname[] = rocketName + RocketNumber + "R.txt";
char newname[] = NameChoice + NumberChoice + "R.txt";
if (std::rename(oldname, newname) != 0) {
perror("Error renaming file");
}
This returns the error "[cquery] array initializer must be an initializer list or string literal".
How can I use std::rename or any other file renaming function that allows me to rename any files I want without hardcoding them in?
This has little to do with std::rename, and everything to do with how to interpolate variables into a string. A simple solution is to use std::string. It has overloaded operator + that can be used to concatenate substrings.
If you want to make the program a bit fancier, C++20 added std::format:
std::string oldname = std::format("{}{}R.txt", rocketName, RocketNumber);
std::string newname = std::format("{}{}R.txt", NameChoice, NumberChoice);
if (std::rename(oldname.c_str(), newname.c_str()) != 0) {
P.S. I recommend using std::filesystem::rename instead since it has better ways of handling errors in my opinion.

Setting source filename in C++ target

I have a code preprocessor which inserts a #line directive in the source code. The directive contains a filename, line number, and character position. I have a lexer rule for the #line directive that calls a function called newFile. The newFile function sets the lexer line number and character position. But, I don't see a way to set the source name. There are functions for getting the source name, but not setting it. I tried setting the input stream source name, but that didn't seem to work (I have an errorListener that gets the filename from recognizer->getInputStream()->getSourceName() but it always returns the initial filename).
My code is (C++ target):
preprocessor pp(_defines, _incpaths);
ANTLRInputStream input(pp.preprocess(filename));
myLexer lexer(&input);
CommonTokenStream tokens(&lexer);
myParser parser(&tokens);
antlr4::tree::ParseTree* tree = parser.start();
And, the newFile code is:
void myLexer::newFile (std::string newFilename, int newLine, int newPos)
{
static_cast<ANTLRInputStream*>(_input)->name = newFilename; // doesn't work
setLine(newLine);
setCharPositionInLine(newPos);
}
Thanks for any and all help.
There's no built-in functionality like that. Keep this information in a separate structure and manage changes there. The input stream name is just a convenient feature, which is not flexible enough for that kind of processing.
Thanks for the info. I tried a few different ways to store file/location information in a separate structure, but it quickly got overly complex.
I resolved the problem by taking advantage of Antlr's line tracking functionality. I stored the filename in a list, then encoded the list index of the filename into the line number.
int fileIndex = filename_list.size();
filename_list.append(filename);
int line = (fileIndex << 20) + newLine;
setLine(line);
setCharPositionInLine(newPos);
Then, in the errorListener, or AST builder, it's easy to access the filename:
void errorListener::syntaxError(Recognizer* recognizer......)
{
int fileIndex = line >> 20;
line &= 0xFFFFF;

Visual C++ Win32 Console application printf output on multiple lines within while loop

I am trying to display data on multiple lines in my console application using printf. The following code displays the data like this:
Default Data=00000000 ACP Status Request=00000000 ACP VHF1 Data=00000000
What I need is:
Default Data=00000000
ACP Status Request=00000000
ACP VHF1 Data=00000000
When I use \n the data fills the console screen over and over again. Can anyone suggest a solution and explain why the loop is fine and the code works untill I try and goto the next line. Thanks.
while(!_kbhit())
{
/*Read message records*/
msgdefault.data = BTI429_MsgDataRd(msgdefault.addr,hCore);
STAT_REQ.data = BTI429_MsgDataRd(STAT_REQ.addr,hCore);
VHF1.data = BTI429_MsgDataRd(VHF1.addr,hCore);
/*Display values*/
printf("\r");
printf("Default Data=%08lX ",msgdefault.data);
//printf("\n");
printf("ACP Status Request=%08lX ",STAT_REQ.data);
//printf("\n");
printf("ACP VHF1 Data=%08lX ",VHF1.data);
}
You need some function to jump to the start of your screen.
Read your documentation, there may be some function like gotoxy(0,0) or something else.
Try searching for System::Console::SetCursorPosition, this may help you.
Try adding following code in the start of loop before printing anything
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
_COORD p;
p.X = x;
p.Y = y;
SetConsoleCursorPosition(hConsole, p);
But make sure to print some empty spaces after your prints so that the remains of old prints are overwritten.

How to ignore a character through strtok?

In the below code i would like to also ignore the character ” . But after adding that in i still get “Mr_Bishop” as my output.
I have the following code:
ifstream getfile;
getfile.open(file,ios::in);
char data[256];
char *line;
//loop till end of file
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," ”");
while(line != NULL)
{
cout << line << endl;
line = strtok(NULL," ");
}
}//end of while loop
my file content :
hello 7 “Mr_Bishop”
hello 10 “0913823”
Basically all i want my output to be :
hello
7
Mr_Bishop
hello
10
0913823
With this code i only get :
hello
7
"Mr_Bishop"
hello
10
"0913823"
Thanks in advance! :)
I realise i have made an error in the inner loop missing out the quote. But now i receive the following output :
hello
7
Mr_Bishop
�
hello
10
0913823
�
any help? thanks! :)
It looks like you used Wordpad or something to generate the file. You should use Notepad or Notepad++ on Windows or similar thing that will create ASCII encoding on Linux. Right now you are using what looks like UTF-8 encoding.
In addition the proper escape sequence for " is \". For instance
line = strtok(data," \"");
Once you fix your file to be in ASCII encoding, you'll find you missed something in your loop.
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," \"");
while(line != NULL)
{
std::cout << line << std::endl;
line = strtok(NULL," \""); // THIS used to be strtok(NULL," ");
}
}//end of while loop
You missed a set of quotes there.
Correcting the file and this mistake yields the proper output.
Have a very careful look at your code:
line = strtok(data," ”");
Notice how the quotes lean at different angles (well mine do, I guess hopefully your font shows the same thing). You have included only the closing double quote in your strtok() call. However, Your data file has:
hello 7 “Mr_Bishop”
which has two different kinds of quotes. Make sure you're using all the right characters, whatever "right" is for your data.
UPDATE: Your data is probably UTF-8 encoded (that's how you got those leaning double quotes in there) and you're using strtok() which is completely unaware of UTF-8 encoding. So it's probably doing the wrong thing, splitting up the multibyte UTF-8 characters, and leaving you with rubbish at the end of the line.

C++ Text File, Chinese characters

I have a C++ project which is supposed to add <item> to the beginning of every line and </item > to the end of every line. This works fine with normal English text, but I have a Chinese text file I would like to do this to, but it does not work. I normally use .txt files, but for this I have to use .rtf to save the Chinese text. After I run my code, it becomes gibberish. Here's an example.
{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31506\stshfloch31506\stshfhich31506\stshfbi31507\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f2\fbidi
\fmodern\fcharset0\fprq1{*\panose
02070309020205020404}Courier
New;}
Code:
int main()
{
ifstream in;
ofstream out;
string lineT, newlineT;
in.open("rawquote.rtf");
if(in.fail())
exit(1);
out.open("itemisedQuote.rtf");
do
{
getline(in,lineT,'\n');
newlineT += "<item>";
newlineT += lineT;
newlineT += "</item>";
if (lineT.length() >5)
{
out<<newlineT<<'\n';
}
newlineT = "";
lineT = "";
} while(!in.eof());
return 0;
}
That looks like RTF, which makes sense as you say this is an rtf file.
Basically, if you dump that file when you open, you'll see it looks like that...
Also, you should revisit your loop
std::string line;
while(getline(in, line, '\n'))
{
// do stuff here, the above check correctly that you have indeed read in a line!
out << "<item>" << line << "</item>" << endl;
}
You can't read the RTF code the same way as plain text as you'll just ignore format tags, etc. and might just break the code.
Try to save your chinese text as a text file using UTF-8 (without BOM) and your code should work. However this might fail if some other UTF-8 encoded character contains essentially a line break (not sure about this part right now), so you should try to do real UTF-8 conversion and read the file using wide chars instead of regular chars (as Chan suggested), which is a little bit tricky using C++.
It's kind of a miracle that this works for non-Chinese text. "\n" is not the line separator in RTF, "\par" is. The odds that more damage is done to the RTF header are certainly greater for Chinese.
C++ is not the best language to tackle this. It is a trivial 5 minute program in C# as long as the file doesn't get too large:
using System;
using System.Windows.Forms; // Add reference
class Program {
static void Main(string[] args) {
var rtb = new RichTextBox();
rtb.LoadFile(args[0], RichTextBoxStreamType.RichText);
var lines = rtb.Lines;
for (int ix = 0; ix < lines.Length; ++ix) {
lines[ix] = "<item>" + lines[ix] + "</item>";
}
rtb.Lines = lines;
rtb.SaveFile(args[0], RichTextBoxStreamType.RichText);
}
}
If C++ is a hard requirement then you'll have to find an RTF parser.
I think you should use 'wchar' for string instead of 'regular char'.
If I'm understanding the objective of this code, your solution is not going to work. A line break in an RTF document does not correspond to a line break in the visible text.
If you can't just use plain text (Chinese characters are not a problem with a valid encoding), take a look at the RTF spec. You'll discover that it is a nightmare. So you're best bet is probably a third-party library that can parse RTF and read it "line" by "line." I have never looked for such a library, so do not have any suggestions off the top of my head, but I'm sure they are out there.