Home > other >  Why do I get an error for the first statement, but not the second one? (C substring)
Why do I get an error for the first statement, but not the second one? (C substring)

Time:01-30

The goal is to get the first, middle, and last name initials each followed by a period.

string first;
string middle;
string last;
string result;

The expression is typed in the string result.

I typed:

result = first[0]   "."   middle[0]   "." last[0]   ".";

And received an the following error:

invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator ’

But when I remove the "." for the above statement, it compiles without any error.

The solution ended up being:

result = first.substr(0,1)   "."   middle.substr(0,1)   "." last.substr(0,1)   ".";

So my question is that, why do I get a compile error when I add . with string[0], but not when I add . with string.substr(0,1)?

CodePudding user response:

first[0]   "."

In this expression:

  1. first is a std::string.
  2. Therefore, first[0] is a char (some immaterial technical details omitted).
  3. "." is a char [2] (an array of two char values).

In C , it is illegal to add a char value to a char [2], you can't just add char to an array. That's simply not allowed in C . There are various rules about what you can do to what else in C . You can add numerical values to other numerical values. You can add an integer value to a pointer. Finally, a class can define its own operator. That's pretty much it. None of this applies to this expression, hence the compilation error.

Now, if you go back and reread the actual error message that your compiler showed you, it should make perfect sense.

CodePudding user response:

This does not do what you think (you should have tested it):

first[0]   middle[0]   last[0]

Each of those is a single character, and in C , single characters are essentially one-byte integers. So adding them just adds their ASCII values (see https://www.asciitable.com/ for those numbers).

first.substr(0,1) gives you a string, and strings can be concatenated with .

Another way to do what you want is:

result.append(first[0]);
result.append('.');
result.append(middle[0]);
result.append('.');
result.append(last[0]);

That just appends one character at a time. You can also pass strings like result.append("...") if you want. The ' single quote is what makes a literal char instead of a literal string (array of chars).

CodePudding user response:

While your question was answered very well, here are other options that I would prefer over substr.

#include <sstream>
...
std::ostringstream compose;
compose << first[0] << "." << middle[0] << "." << last[0] << ".";
std::string result = compose.str(); 

or also

string result = string(first[0])   "."   string(middle[0])   "."   string(last[0])   ".";
  •  Tags:  
  • Related