文件输入会切断第一个单词

时间:2015-09-15 04:25:44

标签: c++ file-processing

我正在编写一个能够接收输入,创建文件和存储该信息的程序。我成功地完成了这一部分。该程序还应该能够将以前的文件打印到屏幕上。我得到的问题是它切断了文件调用第一行的第一个单词。例如,我会点击n并输入之前的文本文件,例如test.txt,它会打印以下内容:

Kennedy
CSC 201
Computer Science
Mondays and Wednesdays
Scott Davis

何时打印:

John Kennedy
CSC 201
Computer Science
Mondays and Wednesdays
Scott Davis

文件打印我做错了什么?

 #include <fstream>
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <cstdlib>
    #include <cmath>

using namespace std;
int main()
{
    ifstream inData;
    ofstream outData;
    string inFile, outFile, fullName, fileName;
    string courseCode, courseName, courseProfessor, courseHours;
    char answer;
    int counter = 0;
    int courses;

    cout << "Are you creating a new file? y/n" << endl;
    cin >> answer;
    if(answer == 'n')
    {
        cout << "Enter the name of your file." << endl;
        cin >> inFile;
        cin.ignore (200, '\n');
        inData.open(inFile.c_str());
        inData >> fileName;
        cout << inData.rdbuf();
    }
    else if(answer == 'y')
    {
        cout << "Enter the name of your file." << endl;
        cin >> outFile;
        cin.ignore (200, '\n');
        outData.open(outFile.c_str());
        cout << "What is your full name?" << endl;
        getline(cin, fullName);
        outData << fullName << endl;
        outData << endl;
        cout << "How many courses are you taking?" << endl;
        cin >> courses;
        while(courses > counter)
        {
            cin.ignore (200, '\n');
            cout << "What is the code for your class?" << endl;
            getline(cin, courseCode);
            outData << courseCode << endl;
            cout << "What is the name of the course?" << endl;
            getline(cin, courseName);
            outData << courseName << endl;
            cout << "What days and time periods do you take this course?" << endl;
            getline(cin, courseHours);
            outData << courseHours << endl;
            cout << "What is the name of your professor?" << endl;
            getline(cin, courseProfessor);
            outData << courseProfessor << endl;
            outData << endl;
            counter++;
        }
    }
    inData.close();
    outData.close();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

inData >> fileName;

之后,您的问题是inData.open(inFile.c_str());

它会将第一个单词读入fileName并移动当前文件位置。