1

I'm attempting to cast ASCII numbers to their corresponding letters of the alphabet using a sentinel controlled loop.

The compiler gives me the error next to cout:

Invalid operands to binary expression 
('std::__1::ostream' (aka 'basic_ostream<char>') and 'vector<char>')

I'm using XCode. This is my current code:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){
    int num;
    char intermediary;
    vector<char> Letters;
    cin>>num;
    while (num!= -1){
        intermediary=char(num);
        Letters.push_back(intermediary);
        cin>>num;
    }
    cout<<Letters<<endl;
    return 0;
}
Devapploper
  • 6,062
  • 3
  • 20
  • 41
alwaystuck
  • 13
  • 3

1 Answers1

0

The std::vector does not have overload for the operator<<, so when you have the cout << Letters, we can say, that the vector does not have definition for what to do, when the << is applied to it.

Some time later, you will know that classes can define an appropriate behavior when an operator is applied to them. These definitions will be just like regular functions, with only difference of having special names. As a result, operators like << for such types (non-built-ins) are essentially just functions, with return types, bodies, and parameter lists.

If you want to print all the elements in a vector you should look toward this approach:

// ...other code as before
for (const auto &c : Letters) // A range for, goes over the whole vector
    std::cout << c;
// ...

Also, you should change the condition to this: while (cin>>num). So overall program should look like this:

int main(){
    int num;
    char intermediary;
    vector<char> Letters;
    while (cin>>num) { // Until valid input, to stop press Ctrl+D (End Of File)
        intermediary=char(num);
        Letters.push_back(intermediary);
    }
    for (const auto &i : Letters)
        cout << i;
    return 0;
}

Also note, that printable ASCII characters start from the number 32.

You may learn more about the range for in here (and many in many other places).

rawrex
  • 4,044
  • 2
  • 8
  • 24
  • This got ride of all error messages, and the program builds successfully, thank you. However, the program doesn't print anything at all now. Only some whitespace and then, "Program ended with exit code: 0". What may the issue be? – alwaystuck Jun 20 '21 at 12:27
  • @alwaystuck great then! Check the latest edit. – rawrex Jun 20 '21 at 12:36