2013-10-15 132 views
0

我試圖從單個文件中提取信息,並使用一條信息(在此參考文獻中,它將成爲某人的主要信息)我想將這些信息導向四個其他文件(根據專業)。對不起,如果這可能對你很明顯,但我真的很喜歡這個。這是我到目前爲止:如何從一個文件中提取信息並將信息分割爲四個其他文件?

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

int main() 
{ 
    double studNum; 
    float GPA; 
    string nameL; 
    string nameF; 
    char initM; 
    char majorCode; 
    ifstream inCisDegree; 
    ofstream outAppmajor; 
    ofstream outNetmajor; 
    ofstream outProgmajor; 
    ofstream outWebmajor; 

    inCisDegree.open("cisdegree.txt"); 
    if (inCisDegree.fail()) 
{ 
    cout << "Error opening input file.\n"; 
    exit(1); 
} 
    outAppmajor.open("appmajors.txt"); 
    outNetmajor.open("netmajors.txt"); 
    outProgmajor.open("progmajors.txt"); 
    outWebmajor.open("webmajors.txt"); 

    while (inCisDegree >> studNum >> GPA >> nameL >> nameF >> initM >> GPA >> majorCode); 

    inCisDegree >> studNum >> nameL >> nameF >> initM >> GPA >> majorCode; 
    cout.setf(ios::fixed); 
    cout.setf(ios::showpoint); 
    cout.precision(2); 

這基本上就我得到。我還有一點點,但只是讓我看看它是否有效。似乎studNum(文件中的學號)確實能夠工作,但是,其他一切似乎都無法正常工作。在確定如何正確地將信息放入四個文件之一中時,我也遇到了一些問題。謝謝你的幫助。我一直在努力工作幾個小時,但我的想法一直在空白。

編輯:在輸入文件中的信息是這樣的:10168822湯普森瑪莎W¯¯3.15

翻譯爲:studNum,NAMEL,NAMEF,initM,GPA,majorCode

回答

0

在該行展望

while(inCisDegree >> studNum >> GPA >> nameL >> nameF >> initM >> GPA >> majorCode); 

因爲你在最後有一個分號,這不會是一個循環(假設它只是這種測試方式,但我想我會提到它)。

但是與該行的主要問題是,您所指定的文本文件是格式

studNum, nameL, nameF, initM, GPA, majorCode 

哪裏這裏,你正試圖從閱讀中

studNum, GPA, nameL, nameF, initM, GPA, majorCode 

拆開來讀值爲兩次,第一次讀入GPA嘗試將string讀入float,並且這可能會在<iostream>(我不確切知道行爲是什麼,但不起作用)內的某處發生異常。這是打破你的閱讀和其餘的變量不會從文件中讀入。

這段代碼應該做你想做的事。

我已經改變studNumdoublelong,你似乎沒有任何理由爲它使用double,並在所有的情形產生你很可能使用unsigned int爲8位數字不會溢出2^32無論如何。

#include <iostream> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 

int main() { 
    long studNum; 
    float GPA; 
    string nameL; 
    string nameF; 
    char initM; 
    char majorCode; 

    cout.setf(ios::fixed); 
    cout.setf(ios::showpoint); 
    cout.precision(2); 

    ifstream inCisDegree; 
    ofstream outAppmajor; 
    ofstream outNetmajor; 
    ofstream outProgmajor; 
    ofstream outWebmajor; 

    inCisDegree.open("cisdegree.txt"); 
    if (inCisDegree.fail()) { 
     cout << "Error opening input file.\n"; 
     exit(1); 
    } 

    outAppmajor.open("appmajors.txt"); 
    outNetmajor.open("netmajors.txt"); 
    outProgmajor.open("progmajors.txt"); 
    outWebmajor.open("webmajors.txt"); 

    while (inCisDegree.good()) { 
     string line; 
     getline(inCisDegree, line); 
     istringstream sLine(line); 

     sLine >> studNum >> nameL >> nameF >> initM >> GPA >> majorCode; 

     cout << studNum << " " << nameL << " " << nameF << " " << initM << " " << GPA << " " << majorCode << endl; 
     // this line is just so we can see what we've read in to the variables 
    } 
} 
相關問題