Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 02.11.2013, 19:23   #1
elCamino
Новичок
Джуниор
 
Регистрация: 01.11.2013
Сообщений: 6
По умолчанию Последняя строка из списка выводится 2 раза, С++

Добро время суток! Помогите пожалуйста новичку опять. язык С++
Есть текстовый файл income.txt, c текстом:
Код:
Miss Informed
125432  32560.0
Sweet Tooth
5432  9500
Bad Data
1255  -4500.0
John Smith
1225  3500.0
Nancy Brown
1555  154500.00
Пограмма читает содержимое файла, распихивает его по переменным.
Потом обратабывает, выводит на экран и пишет в output.txt
Вопрос
При вытаскивании информации из текстового файла последняя строчка
"Nancy Brown 1555 154500.00" повторяется 2 раза, как от этого избавиться.
Пробовал while (inputFile >> name >> lastName >> id >> income)
но тогда не получается проверка на пустой файл...
Как решить проблему, посоветуйте пожалуйста
Код:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
void Header(ofstream &);
void getIputFile(string , ifstream &);
void getOutputFile(string, ofstream &);
void showResult(int, string, string, double, double, double, ofstream&);
void incomeCheck(int, string, string, double, ofstream&);
void idCheck(int, string, string, double, ofstream&);
int main ()
{
	// Initializing varialbles
	ifstream inputFile;
	ofstream outputFile;
	string filenameIn, filenameOut, name, lastName;
	int id, counter = 0, counter2=0;
	double income,netIncome, taxes;
	// Open input file
	getIputFile(filenameIn, inputFile);
	// Check inputfile for wrong name or location
	while(inputFile.fail())
	{
		inputFile.clear();
		cout<<endl<<"\aError opening the inputfile! Please try again"<<endl<<endl;
		cout<<"Enter the name of the filename: ";
		getline (cin,filenameIn);
		inputFile.open(filenameIn.c_str());
	}
	// Open output file
	getOutputFile(filenameOut, outputFile);
	// Check output file for wrong name or location
	while(outputFile.fail())
	{
		cout<<endl<<"\aError opening the output file! Please try again"<<endl<<endl;
		cout<<"Enter the name of the output file: ";
		getline (cin, filenameOut);
		outputFile.open(filenameOut.c_str());
	}
	// Show Header
	Header(outputFile);
	// Reading data from the input file
	while (!inputFile.eof())
	{	
		inputFile >> name >> lastName >> id >> income;
		// Processing the data
		if (income <= 3500 && income>0)
		{
			if (id > 0 && id<9999)
			{
				netIncome = income;
				taxes = 0;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck(id, name, lastName, income, outputFile);
			}
		}
		else if (income > 3500 && income <= 8000)
		{
			if (id > 0 && id<9999)
			{
					taxes = (income-3500)*0.06;
				netIncome= income - taxes;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck(id, name, lastName, income, outputFile);
			}		
		}
		else if (income > 8000 && income <= 20000)
		{
			if (id > 0 && id<9999)
			{
				taxes = (income-8000)*0.11+270;
				netIncome = income - taxes;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck(id, name, lastName, income, outputFile);
			}
		}
		else if (income > 20000 && income <= 34000)
		{
			if (id > 0 && id<9999)
			{
				taxes = (income - 20000) * 0.17 + 1590;
				netIncome = income - taxes;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck(id, name, lastName, income, outputFile);
			}
		}
		else if (income > 34000 && income <= 54000)
		{
			if (id > 0 && id<9999)
			{
				taxes = (income-34000 ) * 0.24+3970;
				netIncome = income - taxes;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck( id,  name, lastName,  income,  outputFile);
			}		
		}
		else if (income > 54000)
		{
			if (id > 0 && id<9999)
			{
				taxes = (income-54000) * 0.32+8770;
				netIncome = income - taxes;
				showResult(id, name, lastName, income, taxes, netIncome, outputFile);
			}
			else
			{
				idCheck(id, name, lastName, income, outputFile);
			}	
		}
		else
		{
			incomeCheck(id, name, lastName, income, outputFile);
		}
		counter++;
	}
	// Check for empty file
	if (counter=0)
	{
		for(int i=0; i<3;i++) //for fun
					cout<<"\n\n\a ---->The input file is empty. goodbye!<----\n\n";
				exit(0);
	}
	// Close I/O files
	inputFile.close();
	outputFile.close();
	cout << endl << endl;
	return 0;
}
elCamino вне форума Ответить с цитированием
Старый 02.11.2013, 23:55   #2
Son Of Pain
Участник клуба
 
Регистрация: 23.12.2010
Сообщений: 1,129
По умолчанию

Если в конце файла будет пустая строка - eof() перед началом последней итерации цикла вернет false, cin попытается прочитать данные которых нет, поток перейдет в ошибочное состояние, и в переменных останутся старые значения. Ты не проверяешь ошибки в цикле, потому последняя строчка и выводится два раза.

Проще всего, действительно, написать
Код:
while (inputFile >> name >> lastName >> id >> income)
.
А проверка на пустой файл не работает, потому что у тебя пропущен второй знак = в условии )
Son Of Pain вне форума Ответить с цитированием
Старый 03.11.2013, 04:44   #3
elCamino
Новичок
Джуниор
 
Регистрация: 01.11.2013
Сообщений: 6
По умолчанию

Спасибо за ответ,
помогло.
elCamino вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
как узнать что в DBGrideh выделенная последняя строка. scroyler БД в Delphi 23 17.02.2012 17:06
Как узнать равна ли последняя строка 2 страницы документа знаку Enter Jaroslav Microsoft Office Word 1 13.08.2010 20:53
Дописать функцию последняя строка kipish_lp Microsoft Office Excel 5 05.07.2010 07:12
последняя строка 0mega Microsoft Office Excel 4 02.06.2010 22:07
макрос замена значений последняя не занятая строка marc-nikita Microsoft Office Excel 2 07.02.2010 12:25