无法使outfile在Windows中的C++中工作

Cannot get outfile to work in C++ in Windows

本文关键字:中的 C++ 工作 Windows outfile      更新时间:2023-10-16

由于某些原因,outfile在Windows中没有输出txt文件。它在Mac上运行良好(下面代码中注释的行(,但在Windows中我无法将其输出。如有任何指导,我们将不胜感激。谢谢


#include <iostream>
#include <fstream>
using namespace std;
int iNumberOfEmployees(); // this function prompts the user for the number of employees.
int iMissedDays(int employees); // this function prompts the user for the number of days each employee missed and returns the total.
double dAverageMissedDays(int employees, double missedDays); // this function calculates the average missed days per employee.
int main() {
    int iGetEmployees = iNumberOfEmployees();
    int iGetMissedDays = iMissedDays(iGetEmployees);
    cout << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays) << endl;
    // outputs results to a text file
    ofstream outfile;
//  outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
    outfile.open ("C:CS140Project 3output.txt");
    if (outfile.is_open()) {
      outfile << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays);
      outfile.close();
    }
    else {
      cout << "Error opening file" << endl;
    }
}
int iNumberOfEmployees () {
    int iTotalEmployees = 0;
    // loop checks that the user doesn't enter a negative number of employees
    while (iTotalEmployees <= 0) {
        cout << "Enter the number of employees: ";
        cin >> iTotalEmployees;
    }
    return iTotalEmployees;
}
int iMissedDays (int iEmployees) {
    int iTotalMissedDays = 0;
    int iIndividualMissedDays;
    // loop asks the user the missed days for each individual employee
    for (int i = 1; i <= iEmployees; i++) {
        iIndividualMissedDays = -1;
        // loop checks that user doesn't enter a negative number
        while (iIndividualMissedDays < 0) {
            cout << "Enter employee " << i << "'s number of missed days: ";
            cin >> iIndividualMissedDays;
        }
        iTotalMissedDays += iIndividualMissedDays;
    }
    return iTotalMissedDays;
}
double dAverageMissedDays (int iEmployees, double dMissedDays) {
    return dMissedDays / iEmployees;
}

在windows中,文件路径由分隔,如果需要将文件路径作为参数传递给函数,还需要额外的

编辑:根据@Benjamin Lindley的说法,只要路径正确,前斜杠也可以在Windows上使用。

在Linux中也没有根目录/

outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");

尝试将字符串"/Users/chrisrukan/Documents/CS140/Project 3/output.txt"替换为windows文件路径格式,即从磁盘名称开始的绝对路径。例如

"C:\Users\chrisrukan\Documents\CS140\Project 3\output.txt"

`"C:/Users/chrisrukan/Documents/CS140/Project 3/output.txt"`

确保这些目录确实存在。

C++中的反斜杠实际上是语言语法,例如,n表示:新行,\t表示:tab,为了在字符串中真正有一个"\"(现在有一个\ C、\ p和\ o,顺便说一下,它们都被认为是一个字符(,必须键入两个\,例如

#include <iostream>
int main() {
    std::cout << "\";
}

输出:


同样只是一个提示,文件将自动(默认情况下,如果没有指定其他路径(输出/写入可执行文件存储的任何位置。