Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 347 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a way to specify how many characters of a string to print out using printf()?

#1
Is there a way to specify how many characters of a string to print out (similar to decimal places in `int`s)?

printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");

Would like it to print: `Here are the first 8 chars: A string`
Reply

#2
printf(....."%.8s")
Reply

#3
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
Reply

#4
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;
Reply

#5
Print first four characters:

`printf("%.4s\n", "A string that is more than 8 chars");`

See [this link][1] for more information (check .precision -section)

[1]:

[To see links please register here]

Reply

#6
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through