0

In this project the user can type in a text(maximum 140 characters). so for this limitation I once used getline():

  string text;
  getline(cin, text);
  text = text.substr(1, 140);

but in this case the result of cout << text << endl; is an empty string.

so I used cin.get() like:

cin.get(text, 140);

this time I get this error: no matching function for call to ‘std::basic_istream::get(std::__cxx11::string&, int)’

note that I have included <iostream>

so the question is how can I fix this why is this happening?

1 Answers1

0

Your first approach is sound with one correction - you need to use

text = text.substr(0, 140);

instead of text = text.substr(1, 140);. Containers (which includes a string) in C/C++ start with index 0 and you are requesting the string to be trimmed from position 1. This is perfectly fine, but if the string happens to be only one character long, calling text.substr(1, 140); will not necessarily cause the program to crash, but will not end up in the desired output either.

According to this source, substr will throw an out of range exception if called with starting position larger than string length. In case of a one character string, position 1 would be equal to string length, but the return value is not meaningful (in fact, it may even be an undefined behavior but I cannot find a confirmation of this statement - in yours and my case, calling it returns an empty string). I recommend you test it yourself in the interactive coding section following the link above.

Your second approach tried to pass a string to a function that expected C-style character arrays. Again, more can be found here. Like the error said, the compiler couldn't find a matching function because the argument was a string and not the char array. Some functions will perform a conversion of string to char, but this is not the case here. You could convert the string to char array yourself, as for instance described in this post, but the first approach is much more in line with C++ practices.

Last note - currently you're only reading a single line of input, I assume you will want to change that.

atru
  • 3,323
  • 2
  • 16
  • 16