如何在循环中将变量分配给iftstream文件内容。 (C ++)

时间:2016-03-20 03:00:08

标签: c++

我创建的程序可以输出orders.txt文件中歌曲的标题,艺术家和价格。

我很难为内容分配变量并成功将它们输出到控制台。

订单列表的一个例子是:

Undead
Hollywood Undead
4.50
Paradise Lost
Hollywood Undead
3.00
Hello
Adele
5.00
Out Of Control
Hoobastank
6.00

我目前正在使用while循环输出所有内容。我知道我需要将getline用于标题和艺术家的单独变量。我也知道需要将价格定为int。

不幸的是,当我调试代码时,循环不会结束或格式化已关闭。我正在使用iomanip与setw()

请帮助!我尝试将价格作为字符串,然后将其转换为int。

这是我的源代码:

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

using namespace std;

int main()
{

ifstream inputFile;
inputFile.open("Orders.txt");
int number, price, totalNum = 0;
double total;
string title, artist;

cout << left << setw(36) << "Title";
cout << setw(22) << "Artist" << left << "Price" << endl;
while (!inputFile.eof())
{
    getline(inputFile, title);
    getline(inputFile, artist);
    inputFile >> price;
    cout << left << setw(36) << title;
    cout << setw(22) << artist << left << "$" << price << endl;

}
inputFile.close();

system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:0)

你试过这个:

while (inputfile >> title)
{
    getline(inputFile, artist);
    inputFile >> price;
    cout << left << setw(36) << title;
    cout << setw(22) << artist << left << "$" << price << endl;
}

也许无限的loob正在由文本文件

的某种不良内容引起

答案 1 :(得分:0)

您的循环条件很可能是导致您出错的原因。这是您的代码,并进行了一些调整,使其能够正常工作。我通过更改发表评论以解释它们。

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

using namespace std;

int main()
{

    ifstream inputFile;
    inputFile.open("Orders.txt");
    int number, price, totalNum = 0;
    double total;
    string title, artist;

    if (inputFile.is_open())
    {
        cout << left << setw(36) << "Title";
        cout << setw(22) << "Artist" << "Price" << endl; // No need to declare 'left' again
        while (getline(inputFile, title))  // Change to 'getline(inputFile, title)'
        {
            getline(inputFile, artist);
            inputFile >> price;
            inputFile.ignore(99999, '\n');  // Discard newline char for next getline
            cout << left << setw(36) << title;
            cout << setw(22) << artist << left << "$" << price << endl;
        }
        inputFile.close();
    }

    system("pause");
    return 0;
}

编辑

您的代码无法正常运行的主要原因是getline的工作方式与>>运算符的工作方式有关。当您调用getline时,它将丢弃换行符。但是,>>运算符不会执行此操作。所以这就是正在发生的事情...

[Example file below]

v [Starts reading from here]
Line1\n <-- [getline() gets rid of '\n']
Line2\n <-- [getline() gets rid of '\n']
10      <-- ['>>' does NOT get rid of '\n']

v [Starts second loop from here]
\n      <-- [This was leftover from '>>' and getline gets it]
Line3   <-- [Second getline() is processing the first line here]
Line4   <-- [Now '>>' tries to put a string in a double (ERROR)]
[Now you get an infinite loop...]