0

由于某种原因,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:\CS140\Project 3\output.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;
}
4

2 回答 2

1

C++ 中的反斜杠实际上是语言语法,例如 \n 表示:换行,\t 表示:制表符,以便在字符串中实际有一个“\”(现在你有一个 \C,\P , 和 \o 顺便说一下,每个都被认为是一个字符)您必须输入两个 \'s,例如

#include <iostream>

int main() {
    std::cout << "\\";
}

输出:

\

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

于 2013-04-30T02:29:23.600 回答
1

在 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"`

确保这些目录确实存在。

于 2013-04-30T02:29:54.657 回答