简体   繁体   English

如何将字符串转换为字符

[英]How to convert a string to char

I am in a beginners programming class and for our assignment we are asked to convert a string of letters/words to braille.我是一名初学者,正在编程 class,对于我们的作业,我们被要求将一串字母/单词转换为盲文。 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.出于某种原因,我似乎无法弄清楚如何让我的字符串将我的输入和 output 每个与其盲文定义相关联的字符分开。

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]我不断收到消息: 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.我只是想展示给我带来问题的部分。

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 :您不需要临时 C 风格的字符串数组cstr ,您需要做的就是使用基于范围的for循环来遍历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 循环,则可以使用迭代器:

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.任何好书(或者任何初学者的书,甚至是坏书)、教程或 class 都应该至少显示上述内容之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM