gpt4 book ai didi

C++ 将文本文件创建/解析为函数

转载 作者:行者123 更新时间:2023-11-28 06:17:11 24 4
gpt4 key购买 nike

我正在尝试从文本文件中获取输入来调用函数。该函数采用 3 个 int 参数。文本文件中的每一行都将包含每个 int 后跟一个空格。如何解析每一行,使用每一行的整数调用一个函数,然后退出循环并关闭文件?任何帮助将不胜感激。

// Here is what the contents of the text file will look like
1 2 3
4 5 6
7 8 9
10 11 12

// here is the function
void readValues(int1, int2, int3)
{
// do something
}

// open text file and parse input. if it does not exist, create file

ifstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

while (file.eof())
{

int a, b, c;
file >> a >> b >> c >> std::endl;
readValues(a, b, c); // first iteration would be readValues(1, 2, 3)

if(file.eof())
{
break;
}
}

file.close();

最佳答案

如果您要读取一个文件,您不应该同时打开它进行写入 (fstream::out) 截断它 (fstream::trunc).

您也不应该在循环条件中测试 eof — 有一些情况 eof 是合适的,但您不会在第一次遇到任何情况几年的 C++ 编程经验。

而且您不需要显式关闭文件,析构函数会处理它。

这样做:

int main()
{
ifstream file("test.txt");

int a, b, c;

while (file >> a >> b >> c)
{
readValues(a, b, c);
}
}

关于C++ 将文本文件创建/解析为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037551/

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