[英]How to convert char to int and find the sum of characters from .txt file
我有一個文本文件:
Carly:Cat:ABCCCCE.
我需要將最后一組字符: ABCCCCE
轉換為整數並顯示它們的總和。 我需要將值設置為:
A = 15, B = 5, C = 6, D = 8, E = 2
我遇到的問題是這些字符在 a.txt 文件中,我非常不熟悉如何只提取該行的最后一個元素。
我試圖創建一個 function 來設置每個字母A through to E
的值,並使用此代碼嘗試將這些字符ABCCCCE
的值加在一起:
int Return_Complexity(char character)
{
switch (character)
{
case 'a':
return 15;
break;
case 'b':
return 5;
break;
case 'c':
return 6;
break;
case 'd':
return 8;
break;
case 'e':
return 2;
break;
default:
return 0;
}
}
void printComplexity()
{
ifstream file("Customers.txt");
vector<int> values;
char character;
while (file >> character)
{
int result = Return_Complexity(tolower(character));
if (result > 0) //if its a-e
values.push_back(result);
}
int Result = accumulate(values.begin(), values.end(), 1); //add together
std::cout << Result << std::endl;
}
int main()
{
printComplexity();
return 0;
}
根據分配給每個字符的值,我希望 output 為:
46
然而,function 返回:
1
任何幫助將不勝感激!
好的,這是您做錯的兩件事。
您已經提到您只想使用該行的最后一段,但沒有代碼來區分最后一段。 因此它添加了“carly”和“cat”中的所有字符。
正如@Slava 在評論中提到的,您需要從文件中讀取每一行並獲取 last :
的 position。
void printComplexity()
{
ifstream file("Customers.txt");
vector<int> values;
string line;
// Read file line-by-line until reaches EOF
while (getline(file, line))
{
// Find last occurrence of `:`
size_t last_pos = line.find_last_of(':');
// Create new string that only contains desired section
// and iterate over it to get value.
string word (line, last_pos);
for (auto& ch : word) {
int result = Return_Complexity(tolower(ch));
values.push_back(result);
}
}
int Result = accumulate(values.begin(), values.end(), 0); //add together
std::cout << Result << std::endl;
}
代碼正在讀取整個文件
因此,即使是 Carly: Ca
t: Ca
。 與 Carly:Cat: ABCCCCE
。
您必須等待character
匹配分隔符:
在這種情況下為:)兩次
然后期待ABCCCCE.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.