String input in C and C++
<p>I want to write a program in C or C++ that asks to user to enter the string at run time of different lengths at different times as given by user (either space separated or non space separated) and store it into an array.  Please give me the sample code in C and C++ for it.</p>

<p>e.g.</p>

<pre><code>1st run:
Enter string
Input: Foo 
</code></pre>

<p>Now <code>char array[]="foo";</code></p>

<pre><code>2nd run:
Enter string
Input:
Pool Of
</code></pre>

<p>Now <code>char array[]="Pool Of";</code></p>

<p>I have tried:</p>

<pre><code>#include&lt;iostream&gt;
using namespace std;

int main()
{
    int n;
    cout&lt;&lt;"enter no. of chars in string";
    cin&gt;&gt;n;
    char *p=new char[n+1];
    cout&lt;&lt;"enter the string"&lt;&lt;endl;
    cin&gt;&gt;p;
    cout&lt;&lt;p&lt;&lt;endl;
    cout&lt;&lt;p;
    return 0;
} 
</code></pre>

<p>But it's not working when the string is space separated.</p>

<p>I have tried this too, but it's not working either.</p>

<pre><code>#include &lt;iostream&gt;
using namespace std;
int main()
{
    int n;
    cout&lt;&lt;"enter no. of chars in string";
    cin&gt;&gt;n;
    char *p=new char[n+1];
    cout&lt;&lt;"enter the string"&lt;&lt;endl;
    cin.getline(p,n);
    cout&lt;&lt;p&lt;&lt;endl;
    cout&lt;&lt;p;
    return 0;
}
</code></pre>
