This code only print characters until char value is 0 but surprisingly it output characters only upto first blank space.
I checked their ASCII values and surprisingly ASCII value of space(' ') character was output by program as 0.
I couldn't get it. Any help is appreciated.

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    try
    {
        char* str=new char[100];    //char* str=new char[100000000000000000];
        cin>>str;
        char*sec=str;
        while(*sec)
        {
            sec++;
            cout<<int(*sec)<<' ';
        }
        cout<<endl;
        cout<<str<<endl;
        delete[] str;
    }
    catch(exception& e)
    {
        cout << "Standard exception: "<<e.what()<<endl;
    }
}

The standard input:

cin >> str;

will read the text that has been inputted only up to the first space character (or new-line, or tab, etc.), and it will store that resulting text (i.e., the first word) as a null-terminated string in the memory pointed to by str. So, the 0 character that your are getting right after the first word is not, in fact, the space character, but it is the null-terminating character that marks the end of the string (i.e., "null-terminated" means that the end is marked by a 0 character).

To read a full line as input, you need to use a function like std::getline() (to read into a C++ string) or cin.getline() (to read into a C-style null-terminated string). Also note that C++ strings are always preferred.

Value of space in ASCII is 32

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.