[英]How to convert a string to char
我是一名初學者,正在編程 class,對於我們的作業,我們被要求將一串字母/單詞轉換為盲文。 出於某種原因,我似乎無法弄清楚如何讓我的字符串將我的輸入和 output 每個與其盲文定義相關聯的字符分開。
這是我的代碼的一部分:
#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|--|";
}
我嘗試在網上查找不同的方法將字符串轉換為字符。 但是,它們似乎都不適用於我的代碼。 我不斷收到消息: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
我不知道如何解決這個問題。 任何幫助,將不勝感激。
注意:這不是我的完整代碼。 我只是想展示給我帶來問題的部分。
您不需要臨時 C 風格的字符串數組cstr
,您需要做的就是使用基於范圍的for
循環來遍歷str1
中的每個字符:
for (char c : str1)
{
switch (c)
{
case 'a':
cout << "|--|\n|* |\n| |\n| |\n|--|";
break;
// etc. for the remaining characters...
}
}
如果不允許使用基於范圍的 for 循環,則可以使用迭代器:
for (auto it = str1.begin(); it != str1.end(); ++it)
{
char c = *it;
// ...
}
或老式的索引迭代:
for (size_t i = 0; i < str1.length(); ++i)
{
char c = str1[i];
// ...
}
任何好書(或者任何初學者的書,甚至是壞書)、教程或 class 都應該至少顯示上述內容之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.