【问题标题】:Error: Expected constructor, destructor, or type conversion before '.' token - Understand fstream错误:“。”之前的预期构造函数、析构函数或类型转换令牌 - 了解 fstream
【发布时间】:2013-04-02 01:11:14
【问题描述】:

我有一个简单的问题。我只是在学习如何使用fstream 在数据文件之间进行打印,而我只是在编译时遇到了问题。我在这段代码的第 11 行和第 20 行遇到了同样的错误。另外,我不太确定我是否在代码末尾正确地从文件中打印。

我得到的错误是:

'错误:'.'之前的预期构造函数、析构函数或类型转换令牌'

对于第 11 行和第 20 行,这是相同的错误,但使用字符 << 而不是 .。我也收到此错误:

“错误:'if' 之前的预期 unqualified-id”

出于某种原因,尽管我很确定我的语法在这些方面是正确的。这些错误是否有某种关联?这是我的 main.cpp 文件:

#include <iostream>
#include <string>

#include <fstream>

using namespace std;

ofstream outFile;
string filename = "test.txt";

outFile.open(filename.c_str() );

if (!outFile) {
  cerr << "File "
       << filename
       << " failed to open for output."
       << endl;
}

outFile << "Hello world!"
        << 2013
        << 3.14
        << "The end."
        << endl;

outFile.close();

ifstream inFile;

inFile.open("test.txt");

if (!inFile) {
  cerr << "File "
       << filename
       << " failed to open for input."
       << endl;
}

int i=0;

while (inFile >> i) {

  cout<< i
  << endl;
  i++;
  cout<< "Year is: "
      << i
      << endl;
  i++;
  cout<< "PI is about: "
      << i
      <<endl;
  i++;
  cout<< i
  <<endl;  
}

【问题讨论】:

  • 从小一点开始,就像一个 hello world 程序,你会看到你缺少什么。
  • 这似乎根本没有任何方法.. ?

标签: c++ file fstream


【解决方案1】:

据我所知,您缺少main 或某种function,否则这不是一个合适的程序,例如:

int main()
{
    ofstream outFile;
    string filename = "test.txt";

    /// rest of your code
 }

写出文件的代码看起来工作正常,下一个问题是当你在这里读回文件时:

while (inFile >> i) 

你有混合数据,首先不是全部int,这样开始可能会更好:

std::string str ;

while (std::getline(inFile, str))
{
        std::cout << str << std::endl ;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2018-12-04
    • 2016-03-14
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多