簡體   English   中英

在C ++中輸入字符時,如何為非單個字符分配值,然后計算值的總和

[英]How to assign values to non single character then calculate the sum of the values when the characters are inputted in c++

我需要分別給字符t1,t2,t3,t4和t5分配值3、4、6、7和9,這樣當您輸入一些字符時,就可以得到這些字符分配值的總和。 例如,如果輸入t1t2則得到7,或者當輸入t1t3t4時得到16,依此類推。 下面是我嘗試過的代碼,但我意識到char變量只能識別單個字符,但是在我的情況下,所有字符都是雙字符(一個字母和一個數字,例如t1),我可能需要使用字符串,但我不知道如何。 任何幫助,將不勝感激。

#include <iomanip>
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char items[] = "t1t2t3t4t5";
int values[] = {3,4,6,7,9};
char entry[100];
std::cout<<"Enter an entry: ";
std::cin>> std::setw ( 100 ) >> entry;

int sum = 0;
for ( int i = 0; entry[i] != '\0'; i++ ) {
for ( int j = 0; items[j] != '\0'; j++ ) {
if ( entry[i] == items[j] )
  sum += values[j];}
cout<< endl;     }
  std::cout<< "The sum is: "<<sum;
    cout<<endl;
}

上面的代碼顯然不會將我的項目視為單個字符,而是將ts與數字分開並將它們單獨對待。

由於問題是關於c ++的,因此建議您使用std :: unordered_map或std :: map(如果需要對變量進行排序,則使用后者)。

例:

std::map<std::string, int> marray;
marray["t1"] = 1;

....

std::string name;
int val;
std::cin >> name >> value;
marray[name] = value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM