What does %.*s represent on printf? [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what does “%.*s” mean in printf in c
I know this question has for sure been asked elsewhere, but searching "%.*s" yields nothing meaningful on SO. Could someone please explain the following line to me?
printf("%.*s", len, buffer);

It limits the output to at most len characters. The . starts the 'precision'; the * says 'use an int from the argument list to determine the precision'. Note that the 'string' (buffer) does not even have to be null terminated if it is longer than len.
All this is easily found in the manual page for printf().

There's a nice table here showing what all the different format specifiers can do for you. For your example, let's say you have a buffer and a length defined as:
char buf[] = "Hello World";
len = 5;
You can use %.*s to print a portion of the full string:
printf("%.*s", len, buffer);
This outputs Hello the first 5 (1 based) characters in this case. Note this is the same as:
printf("%.5s", buffer);

Related

sprintf cause programm stopping [duplicate]

This question already has answers here:
printf with std::string?
(9 answers)
Closed 7 months ago.
std::string sszModName = "kernel32.dll";
std::string WinVersion = "WIN81";
std::string MachineGUID= "ce9e95db-5fda-436a-b29a-f5537702c77d";
char buf[1024];
sprintf(buf, "https://nulln.nullnu-ll.nul/nullnulln/api/ireport.php?module=%s&publisher=%s&win=%s&machineguid=%s", sszModName, "ERROR_HASH_VERIFY", WinVersion, MachineGUID);
This code causes program lag, could you help me figure out why?
Try
sprintf(buf,
"https://nulln.nullnu-ll.nul/nullnulln/api/ireport.php?module=%s&publisher=%s&win=%s&machineguid=%s",
sszModName.c_str(),
"ERROR_HASH_VERIFY",
WinVersion.c_str(),
MachineGUID.c_str());
C strings are not the same as C++ strings. spprintf only uses C strings so you must use .c_str() to turn your C++ strings into C strings.

Why does string concatenation fail when resize is used in cpp? [duplicate]

This question already has answers here:
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 1 year ago.
I came across a scenario where string concatenation is failing in C++. But I don't see a reason for it to fail.
Code sample is as below:
int main()
{
std::string a;
std::string b = "bbbbbbb";
a.resize(10);
for (int i = 0; i <= 5; i++) {
a[i] = 'a';
}
a = a+b;
printf("\n%s\n", a.c_str());
}
It is outputting aaaaaa.
I was expecting it to output aaaaaabbbbb. If I change a.resize(10); to a.resize(5); I am getting the expected output.
Would be helpful if someone could help me in understanding the behaviour?
In addition to the off-by-one error, after concatenation, the contents of a in main are:
aaaaa\0\0\0\0\0bbbbb
So: five 'a' bytes, then five zero bytes, then five 'b' bytes. The string is fifteen bytes long.
printf, like other C functions, doesn't know about this size, and instead takes the length of the string to be until the first zero byte. In your case, that is "aaaaa".
To print the entire string, use something like std::cout. If you're certain you want printf, it is also possible to pass a length to that with the %.*s specifier.
std::string a;
a.resize(10);
gives you a string of size 10 but whose content is undefined.
You set the first 5 character to something specific and append some more characters to the end. But characters 5-10 never get set to something.
In the execution you are seeing, these characters happen to be zero, but printf – as a C style function — considers the appearance of a null character the end of the string. Therefore it stops printing.

Converting an int to String in C++ [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 6 years ago.
I have been working on a project where I need to convert an int8_t variable to a string. I did a bit of reading on this and came to a conclusion that using Strint(int8_t) is an option.
Here is my code:
int8_t matt = 0;
matt += 1;
char string[3]=String(matt);
tft.textWrite(string);// this is used to display text on an lcd display (arduino)
For some reason the method I used did not work so I researched a bit more and found out String(matt) is actually a String object. I don't really know if this is true for a fact. In order for the tft.textWrite(); to work it should look something like this.
Here is the code:
char string[15]= "Hello, World! ";
tft.textWrite(string);
I tried using this also:
char string[3];
sprintf(string, "%ld", matt);
However this did not work.
Can anybody help?
Thanks
It should work fine.
sprintf(string, "%ld", matt);
%ld is used for long int. you are using int8_t which is of range -128 to +128, it is better to use %d.
This code is nearly right
char string[3];
sprintf(string, "%ld", matt);
first
"%ld"
expects a long int as a type you need to find one that can print an 8 bit int. I think its "%hh".
second your
char string[3];
is too short! what if matt is 100 then you use 3 chars but you still need room for the ending zero (and sign). So it should be at least
char string[5];
third the code
sprintf(string, "%ld", matt);
is unsafe as it can write beyond the end of string as it would in your original code, use
snprintf(string, sizeof(string), "%ld", matt);
First you have to keep in mind that there is no String type in C, only fixed sized char arrays (type: char* or char[]). We still call them strings, but keep that in mind.
Your attempt with sprintf looked good to me. Are you shure your environment includes the full C Standard Library ? If not, you will have to code your own format function. If yes, have you included string.h ?
Anyway, try to use snprintf() to precise the size of the target, it is safer.
EDIT: This post applies to the good ol' C style, which I did not see was off topic
the following code should work:
// Example program
#include <iostream>
#include <string>
int main()
{
int8_t matt = 0;
matt += 1;
char string[1];
sprintf(string, "%ld", matt);
std::cout << string << std::endl;
return 0;
}
it prints "1".

Converting char* to int and converting back to the same char array [duplicate]

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Why can't I write to a string literal while I *can* write to a string object?
(4 answers)
Is it possible to modify a string of char in C?
(9 answers)
Closed 8 years ago.
Basically, I am trying to increment the int value of port. This should be easy but I am a little stuck.
It compile fine, but I got this error when I run it:
Access violation writing location 0x001f5834
#include "stdafx.h"
#include "iostream"
using namespace std;
#define TESTING "5002"
int main()
{
char* port = TESTING;
int portint;
sscanf ( port, "%d", &portint );
portint++;
cout << portint << endl; // it works fine up to here, it prints 5003
sprintf ( port, "%d", portint);
return 0;
}
By default, compiler treats string literals as immutable, and an attempt to modify the contents of one results in an access violation error at run time because these strings are put into code segment, and it's read only. In your case, TESTING is a string literal, you can't not change its values. Try:
char port[] = "5002";
Meanwhile, the compiler should have warning on this: when you assign a const char* type to a char* type.
MS C++ compiler has a compiler option regards this: Zc:strictStrings.
You are trying to write "5003" back into "5002". "5002" is a string literal and cannot be written to.
I'll try to find a good duplicate for this question, because it has been asked in many ways, many times.
In your usage, "5002" becomes a static array of characters and as such can not be modified. I believe K&R address this, but I don't have the book in front of me right now. Behavior would be different if you had declared an array.

Reading a string in C++ using scanf [duplicate]

This question already has answers here:
How to scan a string using scanf with C++
(2 answers)
Closed 9 years ago.
I am trying to read a string in C++ using scanf. I tried
char cmd[40];
scanf("%s", cmd);
string str(cmd);
But this gets me a string I want to have plus some non-sense characters.
scanf with the %s specifier will store a null terminator after the input string which prevents garbage characters from getting into the string... unless your code has undefined behavior.
Your issue is likely that the input is overflowing the buffer, resulting in undefined behavior; When using the %s specifier without an appropriate buffer size scanf may write outside the bounds of the buffer. At that point you have no guarantees about how the program will behave.
Never use %s with scanf wihtout providing a buffer size:
char cmd[40];
scanf("%39s", cmd);
string str(cmd);