繁体   English   中英

文件输入切断第一个单词

[英]File Input cuts off first word

我正在编写一个程序,该程序应该能够输入,创建文件并存储该信息。 我已经成功完成了这一部分。 该程序还应该能够将先前的文件打印到屏幕上。 我得到的问题是,它切断了文件调用第一行中的第一个单词。 例如,我将单击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;
}

您的问题是inData >> fileName; inData.open(inFile.c_str());

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM