PDA

View Full Version : Char array problem in c++


teishu
13th February 2007, 02:34 PM
Hi, im struggling with character arrays in c++.
I need to make an array containing what the user enters, here is what i have :

cin >> char word[];
cout <<word << endl;

i don't know the size of the array until they have entered the string.

teishu
13th February 2007, 03:07 PM
here is what i have,

int main(int argc, char *argv[])
{
int size = 0;
cout << "Ascii Converter" << endl;
cout << "By Jason Underhill" << endl;
cout << "-----------------------" << endl;
cout << "Enter the string to be converted to ASCII:" << endl;
string word;
cin >> word;
size = strlen(word);
char w[] = word;




return EXIT_SUCCESS;
}


and here are the errors i get:

/home/teishu/C++/ascii_converter/src/ascii_converter.cpp:41: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’
/home/teishu/C++/ascii_converter/src/ascii_converter.cpp:42: error: initializer fails to determine size of ‘w’

teishu
13th February 2007, 03:57 PM

even with this i get one error:


int main(int argc, char *argv[])
{
int size = 0;
cout << "Ascii Converter" << endl;
cout << "By Jason Underhill" << endl;
cout << "-----------------------" << endl;
cout << "Enter the string to be converted to ASCII:" << endl;
string word;
cin >> word;
size = word.length() - 1;
char wrdar[size] = word;




return EXIT_SUCCESS;
}



/home/teishu/C++/ascii_converter/src/ascii_converter.cpp:42: error: variable-sized object ‘wrdar’ may not be initialized

InfRecursion
13th February 2007, 04:35 PM
Try this:


#include <iostream>

using namespace std;


int main(int argc, char *argv[])
{
int size = 0;
cout << "Ascii Converter" << endl;
cout << "By Jason Underhill" << endl;
cout << "-----------------------" << endl;
cout << "Enter the string to be converted to ASCII:" << endl;
string word;
cin >> word;
size = word.length();
char w[size];
strcpy(w,word.c_str());

cout << "W: " << w << endl;

return EXIT_SUCCESS;
}

teishu
13th February 2007, 04:45 PM
cheers m8, seems to work ok

InfRecursion
13th February 2007, 06:15 PM
Glad I could help :)

teishu
13th February 2007, 06:21 PM
Glad I could help :)

how long have you been programming ?

InfRecursion
14th February 2007, 01:52 PM
how long have you been programming ?

around 17 years or so, professionally for 9.

teishu
14th February 2007, 02:47 PM
ah.. thats why your so good :P

InfRecursion
14th February 2007, 07:33 PM
Nah. I think I'm pretty rusty actually... There are several people here and elsewhere whom are better. After all the years, it gets easier to spot the errors. :) Lots of trial-and-error.

essence
16th February 2007, 12:00 AM
quick question, are you using turbo c++ ?

teishu
16th February 2007, 12:27 AM
no im using Kdev under fedora core 6