I learned recently that you can control the number of characters that printf will show for a string using a precision specifier (assuming your printf implementation supports this).
Option a is the correct answer. %s is used as the format specifier which prints a string in C printf or scanf function. In C, %s allows us to print by commanding printf() to print any corresponding argument in the form of a string. The argument used is "char*" for %s to print.
The basic way is:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
The other, often more useful, way is:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.
You can also use the notation:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
The POSIX specification for printf()
defines these mechanisms.
In addition to specify a fixed amount of characters, you can also use *
which means that printf takes the number of characters from an argument:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char hello[] = "Hello world";
printf("message: '%.3s'\n", hello);
printf("message: '%.*s'\n", 3, hello);
printf("message: '%.*s'\n", 5, hello);
return 0;
}
Prints:
message: 'Hel'
message: 'Hel'
message: 'Hello'
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
%8s would specify a minimum width of 8 characters. You want to truncate at 8, so use %.8s.
If you want to always print exactly 8 characters you could use %8.8s
Using printf
you can do
printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
If you're using C++, you can achieve the same result using the STL:
using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;
Or, less efficiently:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;
Print first four characters:
printf("%.4s\n", "A string that is more than 8 chars");
See this link for more information (check .precision -section)
In C++ it is easy.
std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));
EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.
printf(....."%.8s")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With