逐行读取C 的文件

Reading a file line by line in c++

本文关键字:文件 读取 逐行      更新时间:2023-10-16

我正在尝试在大学中为我的C 类做这个项目,并且我在逐行阅读文本文件,然后将文本从文件输出到控制台。这是我拥有的代码:

void readFile()
{
 cout << "Reading Text File" << endl <<  endl;
 int huge, large, medium, small,  remainder; 
 string line0, line1, line2, line3, line4, line5, line6, numberOrdered;
ifstream fin;

fin.open("DoflingyOrder.txt");
while(getline(fin,numberOrdered))
{
    getline(fin, line1);
    cout << "Name: " << line1  << endl;
    getline(fin, line2);
    cout << "Street Address: " << line2  << endl;
    getline(fin, line3);
    cout << "City, State and Zip Code: " << line3  << endl;
    getline(fin, numberOrdered);
    cout << "Number of Doflingies Ordered: " << numberOrdered  << endl << endl;

}

它忽略了文本文件中的名称,这意味着它是一条线路。有什么建议么?如果有人需要,我可以将文本文件和.cpp文件上传到Dropbox。

这是文本文件的示例:

莱斯利·诺(Leslie Knope) 普利茅斯街1456号 Pawnee,47408 356

Ann Perkins 217 Lowell Drive Pawnee,47408 9

汤姆·哈德福德 689 Lil Sebastian Avenue Pawnee,47408 1100

" Leslie Knope"之前没有空间。

您最终发布的输入...

Leslie Knope 1456 Plymouth Street Pawnee,47408 356

Ann Perkins 217 Lowell Drive Pawnee,47408 9

汤姆·哈德福德689 Lil Sebastian Avenue Pawnee,47408 1100

...揭示您的所有getline s都是错误的,因为它们一次读取了整个行(默认情况下)。

实际上,这是一个相当困难/痛苦的问题。数据,一个完美的解决方案非常困难,因为某些地址可能是说很难与人名称的一部分区分开的建筑物名称,而多词的城镇名称与早期地址详细信息的末尾很难区分。一种合理的教育解决方案可能是:

#define EXPECT(X) 
    do { 
        if (!(X)) throw std::runtime_error("EXPECT(" #X ")"); 
    } while (false)
std::string first, last;
std::string street, town_state_postcode;
int num;
std::string word;
while (fin >> first)
{
    EXPECT(fin >> last);
    while (fin >> word)
    {
        if (word[word.size() - 1] != ',')
            if (street.empty())
                street = word;
            else
                street += ' ' + word;
        else // trailing comma indicates town
        {
            town_state_postcode = word; // town
            EXPECT(fin >> word); // state
            town_state_postcode += ' ';
            town_state_postcode += word;
            EXPECT(fin >> word);
            town_state_postcode += ' ';
            town_state_postcode += word;
            EXPECT(fin >> numberOrdered);
            // SUCCESS use the data here
            // ...
        }
    }
}

上面的代码使这些简单的假设:

  • 名称由名字和姓氏组成

  • 城镇名称是一个单词,带有尾巴逗号

,对于使用现实世界数据的更加精确的解决方案,您需要创建例如可能终止"街道"的单词地址的一部分,例如"驱动器"大街"大街"等等。如果您可以获取创建的文本文件以将某些分离器注入结构的数据(甚至切换到XML之类的东西)。

,它会更好。
string line;
for(int i=0;;i++)
{
if(!getline(fin,line))break;
if(i%4==0)cout<<"Name: "<<line<<endl;
else if(i%4==1)cout<<"Street Address: " << line<< endl;
else if(i%4==2)cout<<"City, State and Zip Code: " << line << endl;
else  cout << "Number of Doflingies Ordered: " << line << endl << endl;
}

我建议使用!跳过名称列。