I
I
Igor Panteleev2018-04-06 12:58:48
C++ / C#
Igor Panteleev, 2018-04-06 12:58:48

Is it possible to use the if statement in this version of the program?

char klas[4];
    {
    if(klas=="231")
    {
    ifstream file ("G:\\1\\ЛР1-231.txt");
        if (file.is_open()) // вызов метода is_open()
    cout << "\n\t Все ОК! Файл открыт!\n\n" << endl;
    else
    {
    cout << "\n\t Файл не открыт!\n\n" << endl;
    return -1;
    }

    fstream inOut  ("G:\\1\\ЛР1-231.txt", std::ios::in | std::ios::app);     
    //Открыли для чтения и записи   if(klas=="231")
            if (inOut) {        //Если файл существует, то
       inOut <<"\n" <<"  "<<fam <<" "" \t "<<im<<"   "" \t "<<ot<<" "" \t " 
    <<klas<<" - класс "<<"  "<<"Оценка  -  "<<A0 <<"    "<< now->tm_mday << 
    '-'
     << (now->tm_mon + 1) << '-'
     <<(now->tm_year + 1900)<< endl;    
    }
    file.close();cout << "\n\t Все ОК! Файл закрыт!\n\n" << endl;
    cin.get();
    system("chcp 1251>nul");
    system("color 1f");
    std::string s;
    std::vector<std::string> lines;

    // читаем файл в контейнер построчно
    std::ifstream in_file("G:\\1\\ЛР1-231.txt", std::ios::in);//"r+",
    while(getline(in_file, s))
    lines.push_back(s);
    in_file.close();

    std::sort(lines.begin(), lines.end()); // сортируем контейнер

    // и записываем отсортированный контейнер в новый файл
    std::vector<std::string>::iterator i = lines.begin();
    std::ofstream out_file("G:\\1\\ЛР1-231.txt", std::ios::out);//"r+",
    for(; i != lines.end(); ++i)
    out_file << *i << std::endl;
    out_file.close();
    return 0;
    }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2018-04-06
@Nipheris

klas=="231"

the comparison will not work as you expect. You are comparing pointers to strings (i.e., pointers to the beginning of memory areas where strings are stored). Because you want to compare the strings themselves, i.e. the contents of the above memory areas, you need to either:
a) use the strncmp function or similar ( this is the C language way ).
b) use the std::string class from the standard library and compare objects of this class. They are already compared by content ( this is the C++ language way )

I
Igor Panteleev, 2018-04-06
@igorekvp

klas(4) is read at the beginning of the program. With what to compare it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question