2014-11-05 3 views
1

Я пытаюсь прочитать из файла с именем «parking.txt», и я хочу прочитать определенные значения из этого файла и вывести их на экран. Как это может быть сделано? Это можно сделать?Как читать из файла в C++

Значения в parking.txt является:

total 5 
One 400 
Five 300 
Ten 200 
Twenty 50 
Quarter 500 

В моем коде я хотел бы заменить «линию» с соответствующим значением из файла.

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

using namespace std; 

int main() 
{ 
    ifstream inputFile ("parking_account.txt"); 
    string line; 

    getline(inputFile, line); 

    cout <<"\n\t-------------------------------------------------------"; 
    cout <<"\n\t======================================================="; 
    cout <<"\n\t    Parking Machine Accounts     "; 
    cout <<"\n\t======================================================="; 
    cout <<"\n\tSr. No. : Bill Name  : Bill Count : Cost(in$) "; 
    cout <<"\n\t-------------------------------------------------------"; 
    cout <<"\n\t  1 : One Dollar  : " << line << " : "; 
    cout <<"\n\t  2 : Five Dollar  : " << line << " : "; 
    cout <<"\n\t  3 : Ten Dollar  : " << line << " : "; 
    cout <<"\n\t  4 : Twenty Dollar : " << line << " : "; 
    cout <<"\n\t  5 : Quarter   : " << line << " : "; 

    cout<<"\n\tTotal bill types found : " <<line <<endl; 
} 

Я попробовал время цикла, который выполняет поиск по строкам, но она выводит 5 из одних и тех же меню с линией обновляется для этого текстового значения. Вот цикл while.

int main() 
{ 
    ifstream inputFile ("parking_account.txt"); 
    string line; 

    getline(inputFile, line); 
    while (inputFile) 
    { 
     cout <<"\n\t-------------------------------------------------------"; 
     cout <<"\n\t======================================================="; 
     cout <<"\n\t    Parking Machine Accounts     "; 
     cout <<"\n\t======================================================="; 
     cout <<"\n\tSr. No. : Bill Name  : Bill Count : Cost(in$) "; 
     cout <<"\n\t-------------------------------------------------------"; 
     cout <<"\n\t  1 : One Dollar  : " << line << " : "; 
     cout <<"\n\t  2 : Five Dollar  : " << line << " : "; 
     cout <<"\n\t  3 : Ten Dollar  : " << line << " : "; 
     cout <<"\n\t  4 : Twenty Dollar : " << line << " : "; 
     cout <<"\n\t  5 : Quarter   : " << line << " : "; 

     cout<<"\n\tTotal bill types found : " <<line <<endl; 
     getline(inputFile, line); 
    } 
} 
+0

Вопросы и фрагмент относятся к различным входным файлам, это исправить – Basilevs

+0

Также удалите пример вывода из цикла, он предназначен для демонстрации, а не для повторного использования. – Basilevs

ответ

1

Попробуйте использовать оператор извлечения >>:

string dummy; //this holds those separators since I have assumed that the numbers are always in the same order 
//alternately, you could extract this two `>>`'s at a time, processing the string that 
//comes befor the number to determine where it should go. For simplicity, I have 
//assumed that the order is always the same. 

int total one, five, ten, twenty, quarter; 
inputFile >> dummy >> total >> dummy >> one >> dummy >> five >> dummy >> ten >> dummy >> twenty >> dummy >> quarter; 

Что это делает сначала распаковывает "Total" строку в dummy. Затем он извлекает значение «5» в целое число total. После этого он извлекает «Один» в dummy, 400 в one как целое число «Два» в dummy, «300» в five как целое число и т. Д. Если я неправильно интерпретировал ваш строковый формат, он должен быть достаточно простым, чтобы изменить приведенное выше, чтобы соответствовать.

Вы можете заменить line переменные в вашем выходе с соответствующим переменным, содержащим значением вы заинтересованы в за стол (one, five и т.д.).

Оператор >> предоставлен istream и полезен для подобных сценариев. (Это полезно отметить, что это работает на cin, а так класс cin «s происходит от istream, так же, как ifstream происходит от istream)

0

Вы должны проверить, если файл может быть открыт. Если вы можете открыть файл, прочитайте значения из файла в своих переменных. Вы могли бы сделать что-то вроде этого:

Если это parking_account.txt:

5 400 300 200 50 500 

И это main.cpp:

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

using namespace std; 

int main() 
{ 
    ifstream inputFile("parking_account.txt"); 
    string line = ""; 
    int total = 0; 
    int one = 0; 
    int five = 0; 
    int ten = 0; 
    int twenty = 0; 
    int quarter = 0; 

    if (!inputFile.is_open()) { 
    cerr << "Could not read from file" << endl; 
    } 
    else { 
    inputFile >> total >> one >> five 
    >> ten >> twenty >> quarter; 
    } 
    getline(inputFile, line); 

    cout <<"\n\t-------------------------------------------------------"; 
    cout <<"\n\t======================================================="; 
    cout <<"\n\t    Parking Machine Accounts     "; 
    cout <<"\n\t======================================================="; 
    cout <<"\n\tSr. No. : Bill Name  : Bill Count : Cost(in$) "; 
    cout <<"\n\t-------------------------------------------------------"; 
    cout <<"\n\t  1 : One Dollar  : " << one << " : "; 
    cout <<"\n\t  2 : Five Dollar  : " << five << " : "; 
    cout <<"\n\t  3 : Ten Dollar  : " << ten << " : "; 
    cout <<"\n\t  4 : Twenty Dollar : " << twenty << " : "; 
    cout <<"\n\t  5 : Quarter   : " << quarter << " : "; 

    cout<<"\n\tTotal bill types found : " << total <<endl; 

    return 0; 
} 
Смежные вопросы