views:

71

answers:

3

Ok guys, i'm very beginner and trying to enter string to a char array using pointers..and then display what i've written.

There're two things i want to ask about. First , if i didn't want to specify a size for the array and just want it to expand to contain all string i've entered ..how is that ? And second after i enter the string and display it...it won't contain the SPACE between word... like if i entered "i love cookies"...it will be displayed as "ilovecookies"..So how to solve that ?

Here's my little code ...

 #include <iostream>

 using namespace std;

 int main()
{

    char *strP , str[100] ;
    strP = str ;

    for(int i =0 ; i<10 ; i++) cin >> *(strP+i) ; 

    for(int i =0 ; i<10 ; i++) cout << *(strP+i) ;


     return 0;
}

sorry for my silly questions, I'm beginner to this language as said and don't want to miss things before moving on .

Thanks in advance .

+1  A: 

cin always stops when it encounters a space. If you're entering character by character, try using getchar().

Vivin Paliath
+1  A: 

1) You need to either use a string object or new if you want to dynamically resize your string.

2) It doesn't contain the spaces because cin reads one words at a time. There are several ways to get around this. The one I would use is switch to using scanf and printf instead of cin and cout. Or, as vivin said, you can use getchar()

EDIT: grammar

David Oneill
Use getline to handle input with spaces in it. Don't use scanf and printf unless you have a better reason; they use varargs so the compiler can't catch type mistakes for you, and they're a source of buffer overflow bugs.
Joseph Garvin
+1  A: 

Arrays can't change their size. You should use std::vector<char>, or even better for strings you would use std::string.

Daniel Earwicker