【问题标题】:ifstream in c++ - compiler issuesc++ 中的 ifstream - 编译器问题
【发布时间】:2015-09-30 16:18:56
【问题描述】:

我正在从 C 转换到 C++,我正在尝试打开并读取一个输入文件,同时将变量分配给读入的值。例如,我有 6 个变量:abcxyz 和我的文件:input.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 &gt;&gt;,如果可以,此示例的语法是什么?

【问题讨论】:

  • 如何编译,更重要的是,如何链接?
  • 将缺失的 int 添加到 main() 后,提供的代码编译正常。
  • 因此,这与文件输入完全无关,而与 C++ 程序的基本编译有关。您应该尝试过 Hello World 并发现问题仍然存在。听起来你在写gcc,而不是g++。您还需要 main 的返回类型。
  • 根据您的 cmets,我找到了解释一切的线程:stackoverflow.com/questions/3178342/… 感谢您的帮助 - 我没有意识到我不能在没有链接的情况下使用 gcc。从现在开始将使用 g++。

标签: c++ fstream ifstream getline


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    试试这个

    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main() {
        int a, b, c, x, y, z;
    
        ifstream infile;
        infile.open("input.dat", ios::in); //Open input.dat in input/read mode 
    
        if (infile.is_open()) {
    
            infile >> a >> b >> c >> x >> y >> z;
            cout << a << b << c << x << y << z;
            infile.close(); //you close here since file would really be open here
            return 0;
        }
        else {
            cout << "Unable to open file." << endl;
        }
    
        return 0;
    }
    

    你可以替换

    infile >> a >> b >> c;

    getline(infile, PUTSTRINGHERE);
    

    如果您想将整行作为字符串变量,但您必须包含

    #include <iostream>
    

    【讨论】:

    • 谢谢,这正是我正在寻找的 >> 运算符。我特别不希望它是一个字符串,所以我将使用第一个。我是否需要指定任何内容来指示新行?(即像我在 C 中使用“\n”所做的那样)还是会自动跳到它看到的下一个非空白字符?
    • 它会自动搜索下一个整数类型,忽略“\n”。如果您在 if 语句中添加 'cout
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2010-12-06
    • 2020-05-17
    相关资源
    最近更新 更多