Link to home
Start Free TrialLog in
Avatar of Ristiisa
Ristiisa

asked on

a Simpel questions - i think

#include <iostream>

using namespace std;

int main(){
     char ip[255];
     cin>>ip;
     cout<<ip;
     return 0;
}

1.
when i input "blaa blaa" then it doesn't output "blaa blaa", it outputs "blaa"

2.
When i declare ip as char* then i get
---------------------------
Microsoft Visual C++
---------------------------
Unhandled exception in Question.exe: 0xC0000005: Access Violation.
---------------------------
OK  
---------------------------

what gives?
Avatar of Mafalda
Mafalda

1. I is because the cin >> inputs the string untill it finds a blank. use getc() or one of the other functions and read char by char

2. It is because that in addtion to declare it as char * you need to allocate memory for the data and delete it when not needed anymore

char * buffer = new char[255];
... use it here ...
delete [] buffer;
Avatar of Ristiisa

ASKER

Tnx for the 2.nd part
but getc() is c function and i'd like to use pure c++
Hi Ristiisa,

You can use cin.get() which inputs 1 character at a time.  Just need to check for the \newline character for the end.
I ment get() ... basic_istream& get(E& c);

Anyway you can use getline and get the whole line ... until a delimiter - default '\n'

char buf[100];
std::cin.getline(buf, 100);
cout << buf;

ASKER CERTIFIED SOLUTION
Avatar of frankieli_98
frankieli_98

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For part 2, since the code has not explicitly called for a constructor for the ip array, it's done automatically, hidden from you.

For the second case, new is used and therefore constructor is called explicitly.  This requires an explicit call of the destructor, by delete, to deallocate the memory previous allocated through new.

Frankie