gpt4 book ai didi

c++ - 从文件读取时如何从行中单独读取每个数字

转载 作者:行者123 更新时间:2023-11-30 04:48:42 24 4
gpt4 key购买 nike

需要有关如何从文件中读取数字并设置行中的每个数字以设置函数的指导

我已经通读了该文件并能够将数字打印到屏幕上,但我对如何能够打印这些数字用于我的特定功能有了一些了解我想使用。比如我有

string line;
while(getline(file,line)){
cout<<line<<"\n";
}
/* What the file is and what it prints out onto the screen
3 6
2 3 2
2 1 6
2 1 4
1 2 3
1 1 2
2 1 8
*/

例如,我想将 36 用于类似

的函数
create_list(int x, int y){}

换句话说,每一行中的每组数字将代表某些函数的输入

最佳答案

从输入行解析可变数量的整数

从问题中不清楚您要做什么。如评论中所述,您可以使用 ifstream 解析文件目录。我很懒,总是用 getline(<ifstream>, str) 解析文件然后使用 istringstream 解析这些行。这样我犯的错误就更少了。

其中一个问题是为什么您有多个行长度。不管怎样,我编写了根据每个输入行是否有 1、2 或 3 个整数来调用的函数。

使用流解析输入的好处在于,流处理器可以解析 int、double 或其他任何类型。

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

int square(std::vector<int> &ints)
{
return ints[0] * ints[0];
}

int rectangle(std::vector<int> &ints)
{
return ints[0] * ints[1];
}

int volume(std::vector<int> &ints)
{
return ints[0] * ints[1] * ints[2];
}

int main()
{

std::ifstream file;
file.open("example.txt");

std::string str;
while (getline(file, str)) {
int parsed_int;
std::vector<int> ints;
int index = 0;

std::stringstream stream(str);
while (stream >> parsed_int) {
ints.push_back(parsed_int);
++index;
}

int answer = 0;
// index is the number of integers read on this line from the file
switch (index) {
case 0:break;
case 1:answer = square(ints);
break;
case 2:answer = rectangle(ints);
break;
case 3:answer = volume(ints);
break;
default:break;
}
std::cout << "Answer is " << answer << "\n";
}
}

关于c++ - 从文件读取时如何从行中单独读取每个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com