a Simpel questions - i think

Ristiisa
Ristiisa used Ask the Experts™
on
#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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
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;

Author

Commented:
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.
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Commented:
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;

#include <iostream>

using namespace std;

int main(){
    char ip[255];

     cin.get(ip, 255);
         
    cout<<ip;
    return 0;
}
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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial