c++ - 如何从输入文件中获取值的总和?

标签 c++

你好,有人能告诉我如何从输入文本文件中只获取音符总和的值(1x20;10x50,100x50 = 总共 111 个音符)吗?

我尝试使用 line.find() 进行一些操作,但是当我有两位/三位数字时,例如 10 x 50 USD ,100 x 50 USD,它给了我错误:

Unhandled exception exception: std::out_of_range at memory location 0x005FDB1C

这是代码

int total=0;
string str2="USD";
std::ifstream file("input.txt");
            if (file.is_open()) {
                std::string line;
                while (getline(file, line)) {

                    if (line.find(str2) != string::npos) {
                        cout << line.substr((line.find("USD")-7))<< '\n';
                        int d = stoi(line.substr((line.find(" x")- 1)));
                        total = total + d;
                        cout << "Total sum: " << total;
                            }
                }
                file.close();
            }

输入文件:


===============================

DATE: 20190929  TIME: 13:55:24

MY ID: mypc

===============================

 Client: 1234
DATE: 2019.09.17 TIME: 14:19:14

0 x 0 USD

1 x 20 USD


 Client: 4567
DATE: 2019.09.17 TIME: 14:21:33

0 x 0 USD

10 x 50 USD

 Client: 8910
DATE: 2019.09.17 TIME: 14:34:25

0 x 0 USD

100 x 50 USD

===============================

最佳答案

使用绝对位置解析字符串很容易出错。 当您有需要存储到类型化变量中的标记分隔值(特别是如果标记是空格)时,使用流(例如 std::stringstream)会更容易。

这是一种方法:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main() {
    int total=0;
    std::string str2="USD";
    std::ifstream file("input.txt");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            if (line.find(str2) != std::string::npos) {
                std::stringstream ss(line);
                int number_of_notes, value;
                std::string operatorX, USD_string;
                ss >> number_of_notes>> operatorX >> value >> USD_string;
                total += number_of_notes;
                std::cout << "Total sum: "<< total << std::endl;
            }
        }
        file.close();
    }
}

关于c++ - 如何从输入文件中获取值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198257/

相关文章:

.net - C++/CLI XMLSerialization 布局

c++ - 使用引用推导模板包中的冲突类型

c++ - 从 ostream 获取 char* 而不进行复制

c++ - 错误 : '__pred' cannot be used as a function

C++ 在 Qt 中传递 Double 添加数字

c++ - 通过分配c内存错误捕获c++异常

c++ - 在 C++ 中为指针赋值

c++ - 以符合 C++ 标准的方式实现 std::malloc

c++ - 在 linux 上学习线程

c++ - C语言的Windows UIAutomatin