debugging 如何在Map中添加一个字符而不需要转换为数字?C++ [关闭]

ffscu2ro  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(68)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由一个错字或一个无法再复制的问题引起的。虽然类似的问题可能是on-topic在这里,但这个问题的解决方式不太可能帮助未来的读者。
15小时前关门了。
这篇文章是编辑并提交审查14小时前.
Improve this question
我试图创建一个函数,它接受一系列由空格分隔的两个字母的输入,并将每个输入添加到一个Map中,其中第一个字母是键,第二个字母是值。
例如,如果我的输入是这样的:
ab cd ef gh ij
我的Map应该是这样的:

['b' ,'a']
['d','c']
['f','e']
['h','g']
['j','i']

但我得到的却是这个

[97 ,'a']
[99,'c']
[101,'e']
[103,'g']
[105,'i']

我还遇到了另一个问题,当我试图运行我的程序时,它不运行循环下面的代码,而是停止运行。

#include <string>
#include <iostream>
#include <map>

using std::string, std::cin, std::cout,  std::endl, std::istream, std::map;

std::map<char,char> encrypt(string const &inpt, map<char,char> &letter_pair){
    
    letter_pair[inpt.at(0)] = inpt.at(1);
    
    return letter_pair;
}

int main(){
    string input;
    
    map<char,char> letter_pair;
    while(cin >> input ){
        
        encrypt(input,letter_pair);

    }
    for(auto pos = letter_pair.begin(); pos != letter_pair.end();++pos){
        cout << pos->first <<":" << pos->second <<endl;
    }
}
7tofc5zh

7tofc5zh1#

下面是一个例子:

std::map<char, char> database;
//...
database['a'] = 'b';

不需要使用ASCII码。

编辑1:真实的程序

#include <iostream>
#include <map>

int main()
{
    std::map<char, char> encryption_table;
    // Initialize
    encryption_table['a'] = 'b';
    encryption_table['c'] = 'd';

    // Print the encryption table.
    std::map<char, char>::const_iterator iter;
    std::map<char, char>::const_iterator iter_end = encryption_table.end();
    for (iter = encryption_table.begin();
         iter != iter_end;
         ++iter)
    {
        std::cout << '['  << iter->first
                  << ", " << iter->second
                  << "]\n";
    }

    return 0;
}

编辑2:根据用户输入建立加密表

#include <iostream>
#include <map>

int main()
{
    std::map<char, char> encryption_table;

    // Create the encryption table from User input
    char from_char;
    char to_char;
    while (std::cin >> from_char >> to_char)
    {
        encryption_table[from_char] = to_char;
    }

    // Print the encryption table.
    std::map<char, char>::const_iterator iter;
    std::map<char, char>::const_iterator iter_end = encryption_table.end();
    for (iter = encryption_table.begin();
         iter != iter_end;
         ++iter)
    {
        std::cout << '['  << iter->first
                  << ", " << iter->second
                  << "]\n";
    }

    return 0;
}

运行示例:

tmatthews$ g++ main.cpp -o main.exe

tmatthews$ ./main.exe
ab cd ef
[a, b]
[c, d]
[e, f]

相关问题