【问题标题】:Ifstream code is not placing the input into the variableIfstream 代码没有将输入放入变量中
【发布时间】:2017-01-09 06:18:28
【问题描述】:

这是我的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{

    //variable init
    ifstream inFile;
    ofstream outFile;
    string toPrint, fileName;
    string var;
    cout << "Enter your save file: "; cin >> fileName;//asks the file name
    cout << "Searching..."<<endl;

    string fileLocation = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";//locates it
    inFile.open(fileLocation.c_str());
    if(!inFile){//checks if the file is existent
        cerr << "Error can't find file." << endl;
        outFile.open(fileLocation.c_str());
        outFile << "Player House: Kubo"<<endl;
        outFile.close();
    }
    cout << "Loaded." << endl;

    inFile.ignore(1000, ':'); inFile >> var; //gets the string and places it in variable named var
    cout << var<<endl;

    //replaces var
    cout << "Enter a string: ";
    cin >> var;

    //saving
    outFile.open(fileLocation.c_str());
    outFile << "Player House: " << var;
    inFile.close();
    outFile.close();
}

这里的问题是我无法将玩家的房子命名为“Kubo”并将其放在名为“var”的变量中。它设法在我的文档中创建文件并设法更改 replaces var 部分中的变量。

【问题讨论】:

  • 同时打开同一个文件两次是危险的。
  • 并非如此。我这样做了,对我以前的文件没有影响。此外,我没有重新打开任何文件。
  • 在打开outFile之前不要关闭inFile,也不要检查打开outFile是否成功。

标签: c++ visual-studio-2015 ifstream ofstream iomanip


【解决方案1】:

据我了解,您需要同时读取和写入文件。试试这段代码

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string fileName;
    cout << "Enter your save file: ";
    cin >> fileName;
    string filePath = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";
    fstream file(filePath, fstream::in | fstream::out | fstream::trunc);   // open modes to read and write simultaneously
    string var;
    if (file.tellg() == 0)
        file << "Player House: Kubo\n";
    file.seekg(14);
    file >> var;
    cout << var << endl;
    file.close();
    return 0;
}

我用tellg()判断文件是否为空,你也可以用

file.peek() == ifstream::traits_type::eof();

【讨论】:

  • 第 16 行显示两个错误 1. 错误(活动)多个运算符“==”匹配这些操作数:..... 2. 错误 C2666 'std::fpos<_mbstatet>: :operator ==': 3 个重载有相似的转换
  • @CraftedGaming 为我工作here
  • 您使用的是什么 IDE?我正在使用 Visual Studio 2015。我尝试使用它运行的 file.peek(),但在输入文件名后它只是给了我一个空白屏幕。
  • Coliru Online Compiler 基于 g++。您可以通过之前评论中的链接访问。
  • if(file.tellg() == static_cast&lt;std::streampos&gt;(0)) 在 Visual Studio 2015 上。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
相关资源
最近更新 更多