-
String C /C++
When i want to use a string in C I tell my compiler to make an array of chars (e.g. char myString[15]), but in C++ theres a special datatype (string) to declare a string.. can i still use the C way in C++ or what would you recommend,
In my opinion the array-approach is the best but then again i started C++ 10 minutes ago.. can anyone tell me a bit more about it?
-
Actually I beg to differ, the string class is much more flexible than an array. The method to use it is below.
Code:
#include <iostream>
#include <string>
#include <stdlib.h>
int main(void)
{
string str;
cout<<"Enter your name.\n";
cin>>str;
cout<<"Hello "<<str<<"!"<<endl;
system("pause");
return 0;
}
The string class method allows you to input as many characters as your memory can handle! :) Whereas to come close you would have to dynamically allocate memory in a string. Or possibly use a the vector array.
I'm about an intermediate programmer to be honest. I use the string method to read from files, it's my prefered method. Although, I do use strings I dynamically allocate its more work doing so.
-
aa
I found a solution to my problem.. I use vectors now :)
-
To get the above code to work you'll need to add the line
Code:
using namespace std;
below the includes. Also, stdlib.h is a deprecated header, it's preffered to use cstdlib.
-
yes i knew that but thanks anyway ;)