@sanek2005

Почему неправильно считывается строка?

я пишу читалку ini файла. начал писать код для чтения секции. вывел в консоль имя полученной секции, и получилось "etscin", хотя ее настоящее имя "test_section". что я делаю не так?

Мой код
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

class IniFile
{
private:
    class Section 
    {
    public:
        class Parameter 
        {
        private:
            string parameterName;
            string value;

        public:

            string GetName() 
            {
                return parameterName;
            }

            string GetValue() 
            {
                return value;
            }

            Parameter(string name, string value)
            {
                this->parameterName = name;
                this->value = value;
            }
        };

        Parameter GetParameterByName(string name) 
        {
            for (int i = 0; i < parameters.size(); i++)
            {
                if (parameters[i].GetName() == name)
                    return parameters[i];
            }
            throw runtime_error("parameter not found!");
        }

        void AddParameter(string name, string value) 
        {
            parameters.push_back(Parameter(name, value));
        }

        string GetName() 
        {
            return name;
        }

        Section(string name)
        {
            this->name = name;
        }

    private:
        vector<Parameter> parameters;
        string name;
    };

    void AddSection(string name) 
    {
        sections.push_back(Section(name));
    }

    vector<Section> sections;
public:
    Section GetSectionByName(string name) 
    {
        for (int i = 0; i < sections.size(); i++)
        {
            if (sections[i].GetName() == name)
                return sections[i];
        }
        throw runtime_error("section not found!");
    }

    void LoadFile(string path) 
    {
        ifstream file;
        file.open(path);

        if (!file.is_open()) 
        {
            throw runtime_error("not doest open file!");
        }
        else 
        {
            while (true)
            {
                string temp = "";
                if (file.get() == '[')
                {                 
                    while (file.get() != ']')
                    {
                        temp += file.get();
                    }
                }
                AddSection(temp);
                break;
            }
        }
        file.close();
    }

#ifdef _DEBUG
    void ShowAllSections()
    {
        for (int i = 0; i < sections.size(); i++)
        {
            cout << sections[i].GetName() << endl;
        }
    }
#endif // DEBUG

    IniFile()
    {

    }
};

int main()
{
    IniFile ini;
    ini.LoadFile("test.ini");
    ini.ShowAllSections();
    return 0;
}
  • Вопрос задан
  • 79 просмотров
Решения вопроса 1
wataru
@wataru Куратор тега C++
Разработчик на С++, экс-олимпиадник.
file.get() читает один символ, возвращает его и переходит к следующему символу ввода. Поэтому код:
while (file.get() != ']')
{
   temp += file.get();
}


читает первый символ, сравнивает со скобкой, потом приписывает в temp второй символ. Потом читает третий и, возможно, приписывает четвертый и т.д. Два вызова file.get() выполняют два чтения.

Правильно делать так:

while ( (с = file.get()) != ']')
{
   temp += с;
}


И похожим образом обрабатывайте '[' перед этим. Читайте в переменную, сравнивайте и не забудьте прочтенный символ засунуть в строку.

Ну, или используйте в условиях istream::peek.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы