Deepak
Deepak

Reputation: 480

printing a string

Is there any function for printing a string up to space, e.g.

char* A = "This is a string."
print(A+5);
output: is

I don't want printing character by character.

Upvotes: 0

Views: 1354

Answers (2)

pmr
pmr

Reputation: 59841

An istream_iterator tokenizes on whitespace:

#include <sstream>
#include <iostream>
#include <iterator>

int main()
{
  const char* f = "this is a string";
  std::stringstream s(f);
  std::istream_iterator<std::string> beg(s);
  std::istream_iterator<std::string> end;
  std::advance(beg, 3);
  if(beg != end)
    std::cout << *beg << std::endl;
  else
    std::cerr << "too far" << std::endl;
  return 0;
}

Upvotes: 1

hmjd
hmjd

Reputation: 122001

printf("%s", buf) prints the characters from buf until a null terminator is encountered: there is no way to change that behaviour.

A possible solution that does not print character-by-character, does not modify the string to be printed and uses the format specifier %.*s which prints the first N characters from a string:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* s = "this is a string";
    char* space_ptr = strchr(s, ' ');

    if (0 != space_ptr)
    {
        printf("%.*s\n", space_ptr - s, s);
    }
    else
    {
        /* No space - print all. */
        printf("%s\n", s);
    }

    return 0;
}

Output:

this

Upvotes: 4

Related Questions