2013-10-15 73 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 
    } 
} 
相关问题