Home > Blockchain >  How do I read in a string and transfer to an array?
How do I read in a string and transfer to an array?

Time:12-09

In this c code, I am taking a string from std::cin and transferring each char item into a char array.

int length; // length of the string
cin >> length;

char charList[length]; // list of the characters
string sequence; // string sequence
cin >> sequence;
for (int i = 0; i < length; i  ) {
    charList[i] = sequence[i];
}

I am not sure if this is the right way to do this or if I am getting something wrong. Are the items out of the indexed string char or string type?

CodePudding user response:

First of all, to answer your doubt about the type: sequence[i] is of type char.

Next, concerning your implementation: to start with, as many people have suggested in the comments, I recommend not getting the length of the string separately from the string itself, because the length of the input string may be different from the declared length, and this may cause all sort of problems (ever heard of the infamous bug heartbleed?)

So, this is the minimum I would do:

  string sequence; // string sequence
  cin >> sequence;
  char charList[sequence.length()]; // list of the characters
  for (int i = 0; i < sequence.length(); i  ) {
      charList[i] = sequence[i];
  }

However, this is still not satisfactorily enough because the above code is not conformant. In other words it is not valid C because C does not really allow variable-length arrays. Depending on the compiler you may get away with it, for instance g accepts it, see https://stackoverflow.com/a/15013295/12175820

But even with g , if you compile with the -pedantic flag you'll get the following warning:

str2arr.cpp:10:8: warning: ISO C   forbids variable length array ‘charList’ [-Wvla]
   10 |   char charList[sequence.length()]; // list of the characters

which compounded to -Werror gives a full-blown compilation error:

str2arr.cpp:10:8: error: ISO C   forbids variable length array ‘charList’ [-Werror=vla]
   10 |   char charList[sequence.length()]; // list of the characters

Plus you might have trouble with more advanced usage, for instance I've just discovered that typeid(charList) won't compile with a variable-length array...

So the real way to do this in C would be using pointers and dynamic-memory allocation, in the heap, using operator new:

  string sequence; // string sequence
  cin >> sequence;
  char* charList = new char[sequence.length()]; // list of the characters
  for (int i = 0; i < sequence.length(); i  ) {
      charList[i] = sequence[i];
  }

the above code is valid C accepted by any compiler.

CodePudding user response:

I think having length as unsigned or size_t might be a better idea than int. For now, if the input to length is 0 or negative numbers, something unexpected might happen.

  • Related