0

I've just started learning C++ and im kinda confused about strings. I first need a input word and save every single char in the certain position of a char-Array. But strings are basically char-Arrays, aren't they? But this does not work:

char word[];
cin >> word[];

Whereas this works but I dont know how to fill the chars into an Array.

string s;
cin >> s;

I've tried this so far, but i got an compile error:

string s;
cin >> s;
char word[] = s;

I'm sorry, I've just started programming and I wonder if anyone has some advice for me :)

  • 2
    Why don't you just use the string `s`? What is the purpose of the `char` array? – juanchopanza Aug 18 '13 at 13:55
  • @juanchopanza "I've just started learning C++" likely a learning exercise to hammer in memory fundamentals and primitives – im so confused Aug 18 '13 at 13:57
  • `std::string` is a library class. Arrays are built-in types that don't have much functionality built into them. – chris Aug 18 '13 at 13:59
  • @imsoconfused Well, that would be a very inefficient way to go about learning. But often beginners just don't know enough about the standard library to make effective use of it, and *think* they need to use plain arrays or `new` everythere. – juanchopanza Aug 18 '13 at 14:00

1 Answers1

0
char word[];

You need to give the size of the array. Then, you can take input to it directly. If you wish to copy read the std::string to the character array, then you need to use safe string copy functions like strncpy. For example -

char word[10];
std::string str("Hello");

strncpy(word, str.c_str(), sizeof(word));

However, std::string is recommended in C++ rather than working with character arrays.

Mahesh
  • 32,544
  • 17
  • 80
  • 111
  • Since the array size is known to be 10 and the `string` holds 5 characters, there is no no need for `strncpy`. If you do use `strncpy` you **must** check that it produced a valid string; if the source string, not counting the terminating `'\0'`, has enough characters to fill the target array, there will be no terminating `'\0'` in the result. Blindly using that array will lead to problems. – Pete Becker Aug 18 '13 at 14:24
  • 1
    Yes, in this example. But I just want the OP to use string safe copy functions. – Mahesh Aug 18 '13 at 14:28
  • Shrug. Write an example that needs it, explain why it needs it, and use it correctly. Using "safe" functions doesn't do you or anyone else any good if you don't use them right. – Pete Becker Aug 18 '13 at 14:29