printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
如果使用 C + + ,可以使用 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;
或者,效率更低:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;