gpt4 book ai didi

c++ - c++ 中的 ifstream - 编译器问题

转载 作者:行者123 更新时间:2023-11-28 02:19:59 25 4
gpt4 key购买 nike

我正在从 C 过渡到 C++,我试图打开并读取一个输入文件,同时将变量分配给读入的值。例如,我有 6 个变量:abcxyz 和我的文件:输入.dat 看起来像这样:

1     2     3
4 5 6

所以在 C 中我会写:

infile = fopen("input.dat","r");
fscanf(infile, "%d \t %d \t %d \n %d \t %d \t %d \n",&a,&b,&c,&x,&y,&z);

我正在尝试使用 ifstream 在 C++ 中做同样的事情,但我在编译一个简单的程序时遇到了问题:

#include <iostream>
#include <fstream>

using namespace std;

main(){
int a, b, c, x, y, z;

ifstream infile("input.dat", ifstream::in); //Open input.dat in input/read mode

if(infile.is_open()){
/*read and assign variables from file - not sure how to do this yet*/
return 0;
} else {
cout << "Unable to open file." << endl;
}
infile.close();

return 0;
}

当我尝试编译它时,我收到了一大堆错误,它们看起来都像这样:

 "Undefined reference to std::cout"

我确定这只是一些愚蠢的错误,但我似乎无法弄清楚。我试图遵循以下示例中描述的语法:http://www.cplusplus.com/doc/tutorial/files/

问题:

1.如何在上述代码中正确使用fstream

2.如何从文件中读取输入并将其分配给变量。我知道这可以用 getline 来完成。是否可以使用提取 operator >>,如果可以,这个例子的语法是什么?

最佳答案

除了不清楚的编译(可能是链接)问题,从流中读取很简单:

infile >> a >> b >> c >> d >> e;

假设您的数据以空格分隔,就可以解决问题。

关于c++ - c++ 中的 ifstream - 编译器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32871059/

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