0

I am in a beginners programming class and for our assignment we are asked to convert a string of letters/words to braille. For some reason I cannot seem to figure out how to make my string separate my input and output each character that is associated with its braille definition.

Here is a portion of my code:

#include <iostream>
#include <cstring>
using namespace std;
int main(){

    string str1;
    getline(cin, str1);

int n = str1.length();
char cstr[n + 1];
strcpy(cstr, str1.c_str());

   if( cstr == 'a')
       cout << "|--|\n|* |\n|  |\n|  |\n|--|";
   if( cstr == 'b')
       cout << "|--|\n|* |\n|* |\n|  |\n|--|";
}

I have tried looking up different ways online to convert strings to char. However, none of them seem to work on my code. I keep receiving the message:error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
I have no idea how to fix this issue. Any help would be appreciated.

Note: This is not my complete code. I just wanted to show the part that is giving me problems.

hanie
  • 1,863
  • 3
  • 9
  • 19
Fooji
  • 71
  • 7
  • 1
    `char cstr[n + 1];` is invalid C++ as C++ doesn't have [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array). Use `std::string` for *all* strings. – Some programmer dude Apr 19 '20 at 03:55
  • As for your problem, do you mean that you want to iterate (loop) over the input string and do some operation on each and every character? Then first of all you need a loop. Then you need a way to get one character at a time from the loop. And I really recommend you to use some kind of mapping or array to map each character to an output string. – Some programmer dude Apr 19 '20 at 03:57
  • There is a difference between single quotes and double quotes. Also, you can't compare C-style strings directly with `==`. You have to use `strcmp`. – eesiraed Apr 19 '20 at 04:01
  • I'm aware that I need to add loops over the input string. My problem is that when it gets to the `if statement` , then the program fails to compile as my input is a `string` and not a `char` – Fooji Apr 19 '20 at 04:04

1 Answers1

2

You don't need the temporary C-style string array cstr, all you need to do is use a range-based for loop to loop over each character in str1:

for (char c : str1)
{
    switch (c)
    {
    case 'a':
        cout << "|--|\n|* |\n|  |\n|  |\n|--|";
        break;

    // etc. for the remaining characters...
    }
}

If you're not allowed to use range-based for loops, then you can use iterators:

for (auto it = str1.begin(); it != str1.end(); ++it)
{
    char c = *it;

    // ...
}

Or old-school index iteration:

for (size_t i = 0; i < str1.length(); ++i)
{
    char c = str1[i];

    // ...
}

Any good book (or really any beginners book at all, even bad ones), tutorial or class should have shown at least one of the above.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621