Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;从文件中读取的反向波兰符号_C++_File_Rpn - Fatal编程技术网

C++ C++;从文件中读取的反向波兰符号

C++ C++;从文件中读取的反向波兰符号,c++,file,rpn,C++,File,Rpn,我有一个包含RPN文本的文件,每一行都是不同的。让我们以第一行为例: 12 2 3 4 * 10 5 / + * + 我需要计算每行的总数。为此,我需要使用stack。它的工作原理是这样的:若有一个数字->将其添加到堆栈中,若是+、-、*或/->则在堆栈上取两个最新的数字,并对它们执行上述操作 问题是,我在读文件的时候被卡住了。我曾考虑将数字和符号存储在一个数组中,但这里还有另一个问题: 如果(数组正在存储字符): array[0] = '1', array[1] = '2', ar

我有一个包含RPN文本的文件,每一行都是不同的。让我们以第一行为例:

12 2 3 4 * 10 5 / + * +
我需要计算每行的总数。为此,我需要使用stack。它的工作原理是这样的:若有一个数字->将其添加到堆栈中,若是+、-、*或/->则在堆栈上取两个最新的数字,并对它们执行上述操作

问题是,我在读文件的时候被卡住了。我曾考虑将数字和符号存储在一个数组中,但这里还有另一个问题:

如果(数组正在存储字符):

array[0] = '1',   
array[1] = '2',  
array[2] = ' ',
如何将其转换为int 12(空格表示它是数字的结尾)?有没有简单快捷的方法? 或者有更好的方法读取文件并将其放入堆栈?

多亏了关于使用字符串存储数据的建议,我做到了这一点,实现如下:

每行前的非第一行的空格是必需的,否则程序将把“\n”与下一行的第一个数字放在一起,这是我们不需要的。

请看一下:

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

void parseLine(const std::string& line) {
    std::stringstream stream(line);
    std::string token;
    while(stream >> token) {
        // Do whatever you need with the token.
    }
}

int main() {
    std::ifstream input("input.txt");
    std::string line;
    while(std::getline(input, line)) {
        parseLine(line);
    }
}
#包括
#包括
#包括
void parseLine(const std::string和line){
std::stringstream(行);
字符串标记;
while(流>>令牌){
//你需要什么就用什么。
}
}
int main(){
std::ifstream输入(“input.txt”);
std::字符串行;
while(std::getline(输入,行)){
行(行);
}
}

使用
std::string
并按空格分割(进入
std::string
数组)?如果输入文件格式保证实体之间至少有一个空格,那么您可以使用
std::ifstream
并读取数字和运算符来
std::string
对象。您不能使用单个字符数组,因为数字可能占用多个字符,例如10和12。将文本存储在
std::string
中,您可以使用
istringstream
将文本转换为数字。
12 2 3 4 * 10 5 / + * + 
 2 7 + 3 / 14 3 - 4 * + 
#include <fstream>
#include <sstream>
#include <string>

void parseLine(const std::string& line) {
    std::stringstream stream(line);
    std::string token;
    while(stream >> token) {
        // Do whatever you need with the token.
    }
}

int main() {
    std::ifstream input("input.txt");
    std::string line;
    while(std::getline(input, line)) {
        parseLine(line);
    }
}