Entering a string of characters using arrays and pointers
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) 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
cin
always stops when it encounters a space. If you're entering character by character, try using getchar()
.
Arrays can't change their size. You should use std::vector<char>
, or even better for strings you would use std::string
.
精彩评论