0

The program I am writing is supposed to accept a social security number in the format ddd-dd-dddd.

My class textbook says that the format to index a specific character from a string is to use variable.at(index)

I used that format unsuccessfully. This is what DIDN'T work:

if ("-" == social.at(2) && "-" == social.at(5)){

It returns "Invalid operands to binary expression ('const std::string' (aka 'const basic_string') and 'std::basic_string::value_type' (aka 'char'))"

After researching previously-asked questions on here, I tried this on a whim, which works:

      if ("-" == string(1, social[2]) && "-" == string(1, social[5])) {

However, I don't know what the difference between the two is. I am specifically confused by:

string(1,

Why is there a 1? Also, why did this work when the syntax I got from my textbook didn't? What method is this? Any help and resources are appreciated!

  • 1
    The original should use single quotes: `'-' == social.at(2)`. Single quotes is a `char`, double quotes is a c string. – Garr Godfrey Feb 16 '22 at 01:18
  • As for `string(1, ...`, you've used a particular `string` constructor used to repeat a single character. It repeats the character in the 2nd parameter as many times as the first parameter. You converted a character to a std::string, then compared to a c string. – Garr Godfrey Feb 16 '22 at 01:20
  • A [String Literal](https://en.cppreference.com/w/cpp/language/string_literal) in this case. – user4581301 Feb 16 '22 at 01:21

0 Answers0