【问题标题】:read lines from file and split them into two numbers and perform calculations and write them into file c++从文件中读取行并将它们分成两个数字并执行计算并将它们写入文件c ++
【发布时间】:2015-10-18 22:18:09
【问题描述】:

!!!!严格没有指针或数组!!

文件中的示例内容。

33 + 20

最多 17 和 53 个

14 减 -5

4 乘以 10

44 - 9

4 * 10

8 / 3

33 + 20

8 除以 3

67 和 83 的最小值

我编写了以下代码来识别关键字,但我无法检索数字

“#includeiostream”

“#includefstream”

“#includestring”

使用命名空间标准;

int main() {

ifstream op;
int s;
string line;
op.open("t.txt");
string f[10] = { "+", "plus", "-", "minus", "/", "divided", "Min", "Max", "*", "times" };

while (!op.eof()) {

    getline(op, line);
    cout << line << endl;
    for (int i = 0; i < 3; i++) {
        s = line.find(f[i]);
        if (s!=-1) {
            if (f[i] == "+" || f[i] == "plus")
                cout << "perform addition" << endl;
            else if (f[i] == "-" || f[i] == "minus")
                cout << "Perform subtraction"<<endl;
            else if (f[i] == "*" || f[i] == "times")
                cout << "Perform multiplication" << endl;
            else if (f[i] == "/" || f[i] == "divided")
                cout << "Perform division" << endl;
            else if (f[i] == "Max")
                cout << "Max" << endl;
            else if (f[i] == "Min")
                cout << "Min" << endl;

        }
    }
}
op.close();
system("pause");

}

【问题讨论】:

  • !!!!严格没有指针或数组!!
  • 字符串字符数组...

标签: c++ string file input


【解决方案1】:

嗯,你有一个好的开始,但你还有一些工作要做。您的循环将(主要)找到要在每一行上执行的操作(注意那个一元减号)。查找操作的操作数会有点棘手,除非您被允许使用正则表达式,否则将涉及一些字符操作。

基本的想法是这样的。从行首开始搜索,直到找到第一个数字。这可以通过多种方式完成,包括使用 isdigit 之类的库函数到更暴力的方法,例如:

if (line[i] >= '0' && line[i]

一旦你找到一个数字,继续积累字符,直到你不再找到一个数字。您找到的数字可以通过多种方式转换为实际数字。你可以使用像atoi这样的库函数,你可以使用stringstream类,你可以使用scanf,或者你可以通过将前一个数字乘以10并添加当前数字来自己构建数字:

int sum = 0;
while (isdigit(line[i]))
{
    sum = sum * 10 + line[i] - '0';
    i++;
}

一旦您停止查找数字,请继续查看该行中的字符,直到找到第二个数字。重复这个过程(上面)来创建你的第二个操作数。如前所述,您将需要处理出现一元减号的情况。此时你应该有你的两个操作数和你的操作符,你可以执行表达式并输出结果。

【讨论】:

  • strtol(const char *nptr, char **endptr, int base) 可以为您进行转换,并为您提供指向数字后第一个字符的指针。使用strtol 库函数比自己编写要好得多,因为它是防弹的。我认为您的循环中已经有一个错误:它应该是sum = ... - '0',而不是'a'。在扫描数字的开头时使用isdigit 将涵盖任何与语言环境相关的极端情况。
  • @PeterCordes 啊,你是对的,当然。手指在自动驾驶仪上。我已经做出改变了。
猜你喜欢
  • 2017-04-27
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 2017-05-10
  • 2020-11-23
  • 2021-01-11
相关资源
最近更新 更多