西里尔输入输出,c ++

时间:2015-03-17 13:50:59

标签: c++ cyrillic

仍处于学习过程中。 我制作了一个小程序:

  1. 使用用户输入制作文件
  2. 阅读文件
  3. 从文件中填充struct,排序,然后创建一个新文件" name sorted.txt"
  4. 这是我的3个案例。当我打开西里尔文本并尝试填充结构,排序并创建一个新文件时出现问题。(使用案例3:...)。如果我的测试正确的话,结构不会填充。 但它正确地制作和阅读文件(案例1,2)

    如果我只使用拉丁字母,程序正在做正确的事情。如果有任何帮助,我的代码是受欢迎的......

    #include "stdafx.h"
    #include "iostream"
    #include <fstream>
    #include "string"
    #include <sys/stat.h>
    #include<clocale>
    #include <Windows.h>
    using namespace std;
    
    #define  MAX 10000// max number of students per list
    
    //void sortStruct(); sorting structure
    //void swap(studentStruct , studentStruct ); helping with sort function
    //void readFile (string );reading a .txt file (ex. Saved list)
    //void printStruct(); printing the struct
    //void fillStruct(string ); filling a struct from a chosen file, helpin with a sort
    //void calculateGrade(ofstream , int ); calcuating average grade, under witch we sort
    //void writeToFile(ofstream , string ,float ); writing to a .txt file
    //void printMenu(); printing a menu to chose from
    
    //for sorting the list
    struct studentStruct{
    string name;
    float grade;
    }student[MAX];
    
    
    static void printMenu()
    {
        //setlocale(LC_ALL, "Russian");
        cout<<"MENU"<<endl<<endl;
        cout<<"1. Добавить новые записи в файл или создать новый файл"<<endl;
        cout<<"2. Распечатайте файл на терминал"<<endl;
        cout<<"3. Сделать отсортированный версию текстового файла"<<endl;
        cout<<"4. Bыход"<<endl<<endl;
        cout<<"Выберите (цифры) :   ";
    }
    inline bool exists_test (const std::string& name) {
        ifstream f(name.c_str());
        if (f.good()) {
            f.close();
            return true;
        } else {
            f.close();
            return false;
        }   
    }
    void writeToFile(ofstream &outputFile, string name,float grade)
    {   
    
        outputFile<<name<<" "<<grade<<endl;
    
    cout << "Готово!\n";
    }
    
    void calculateGrade(ofstream &outputFile, int numProf)
    {
        float sum;
        string name,last;
    
        cout<<endl<<endl;
        cout<<"Введите имя студента : ";
        cin.sync();
        getline(cin,name);
        cout<<endl;
        for(int i=0; i<numProf;i++)
        {
            cout<<"Введите "<<i+1<<". оценку (цифры) : ";
            cin>>sum;
            sum+=sum;
        }
        float grade=sum/numProf; 
    
        writeToFile(outputFile, name,grade);
    }
    
    static void fillStruct(string FileName)
    {
        ifstream rdFile;    //Input Object
        bool i;
        i=exists_test(FileName);
        if(i=true)cout<<"IMA";
        rdFile.open(FileName);
    
        for(int i=0; i<MAX;i++)
        {
            rdFile>>student[i].name;
            rdFile>>student[i].grade;
        }
    
        rdFile.close();
    
    }
    static void printStruct()
    {
    for(int i=0;i<MAX;i++){
            if(student[i].grade!=0)
            cout<<student[i].name<<" "<<student[i].grade<<endl;}
    cout<<"Готово!"<<endl;
    }
    
    
    static void readFile (string FileName)
    {
        ifstream rdFile;    //Input Object
        rdFile.open(FileName);
        cout<<endl;
        string n;
        if (!rdFile)
        {
            cout<<"File could not be open...";exit(1);
        }
        else  
        {   
            while (rdFile && getline(rdFile, n))
            {
                if (n.length() == 0)continue;
                cout<<n<<endl;
            }
        }
        rdFile.close();
        cout<<endl<<"Готово!"<<endl;
        system("PAUSE");
    }
    
    
    void swap(studentStruct &x, studentStruct & y)
    {
        studentStruct temp;
        temp = x;
        x = y;
        y = temp;
    }
    
    static void sortStruct()
    {
        for (int i = 1; i < MAX; i++)
          {
              for (int j = 0; j < MAX-i; j++)
            {
                if (student[j].grade < student[j+1].grade)
                  {
                      swap(student[j].grade, student[j+1].grade);
                      swap(student[j].name, student[j+1].name);
              }
            }    
           }
    }
    
    static void writeStructToFile(string outputFile)
    {
        ofstream rdFile;
        rdFile.open(outputFile);
        for(int i=0; i<MAX; i++)
        {
            if(student[i].grade!=0)
            {
                rdFile<<student[i].name<<" "<<student[i].grade<<endl;
            }
        }
        rdFile.close();
    
        cout<<"Готово!"<<endl;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        bool check;
        int flag=0,numProf,newEntreies;
        string FileName,tempName,n;
        ofstream outputFile;
        ifstream nnn;
        SetConsoleCP(1251);
        SetConsoleOutputCP(1251);
    
        do 
        {
            system("CLS");
            printMenu();
            cin>>flag;
    
            //while(flag!=1||flag!=2||flag!=3||flag!=4){
                //system("CLS");        
                //printMenu();
                //cin>>flag;}
    
            switch(flag)
            {
            case 1 : 
                if(FileName=="exit") {cout<<"Program will exit now..."<<endl; flag=-2;break;}
                else if(FileName=="menu")break;
                cout<<"Выберите имя для нового текстового файла (буквы и цифры):  ";
                cin.sync();
                getline(cin,FileName);
                cout<<"Введите число профессоров (цифры):  ";
                cin>>numProf;
                cout<<"Введите число студентов (цифры) :  ";
                cin>>newEntreies;
                tempName=FileName+".txt";
                check=exists_test(tempName);
                if(check==true)
                    outputFile.open(tempName, std::ios_base::app); 
                else
                    outputFile.open(tempName);
                if(outputFile.fail()) 
                { //if opening fails then end program
                     cout << "Input file opening failed." << endl;
                     exit(1);
                } //exit function from cstdlib library
                system("CLS");
                for(int i=0; i<newEntreies;i++)
                {
                    cout<<FileName<<" "<<numProf<<" "<<newEntreies<<endl<<endl;
                    cout<<"Добавление "<<i+1<<". студента...";
                    calculateGrade(outputFile,numProf);
                    system("CLS");
                }
                    outputFile.close();
                    cout<<"Нажмите любую клавишу для продолжения..."<<endl;
                break;
            case 2 :
                if(FileName=="exit") {cout<<"Program will exit now..."<<endl;flag=-2;break;}
                else if(FileName=="menu")break;
                cout<<"Введите имя файла:  ";
                cin.sync();
                getline(cin,FileName);
                system("cls");
                cout<<"Чтение из файла "<<FileName<<".txt"<<endl;
    
                tempName=FileName+".txt";
                readFile(tempName);
                cout<<"Нажмите любую клавишу для продолжения..."<<endl;
                break;
            case 3 : 
                if(FileName=="exit") {flag=-2;break;}
                else if(FileName=="menu")break;
                system("CLS");
                cout<<endl<<"Изготовление отсортированного файла..."<<endl<<endl;
                cout<<"Выберите файл .txt(буквы и цифры): ";
                cin.sync();
                getline(cin,FileName);
                tempName=FileName+" SORTED.txt";
                fillStruct(FileName+".txt");
                sortStruct();
                writeStructToFile(tempName);
                cout<<endl<<endl<<"Отсортировано версия "<<FileName<<" Готово!"<<endl<<endl;
                cout<<"Нажмите любую клавишу для продолжения..."<<endl;
                system("PAUSE");
                break;
            case 4: cout<< "Program will exit now..."<<endl; flag=-2;break;
            default :cout<<"Program will exit now..."<<endl;flag=-2;break;
    
            }
    
        }while(flag!=-2);
    
        system ("PAUSE");
        return 0;
    }
    

1 个答案:

答案 0 :(得分:1)

没有多看你的示例代码 - 太长,格式太差,太糟糕(根本没有)评论。

  • 您的源文件是什么编码? UTF-8? (我强烈建议,除非你一路走下去并使用带有转义的ASCII-7。)或者它是ISO-8859-5? KOI-8R?还有别的吗?
  • 您是否告诉编译器?

标准实际上只定义了一个非常基本的指令集(基本上没有$@和反引号的ASCII-7)。除此之外的任何内容都由编译器以实现定义的方式解释。您需要明确同意编译器有关源编码的信息,或者需要使用hex / oct转义来保留源ASCII-7并手动强制执行特定编码。

一旦你的文字适合你的编译时环境,就需要你的运行时环境就事情达成一致:

  • 您的终端需要包含带有相应西里尔字形的字体。
  • 当您使用std::cout时,如果您的系统支持(并假设您的文字使用该编码),则应设置类似setlocale( LC_ALL, "ru_RU.UTF-8" )或任何其他UTF-8语言环境的内容。 &#34;俄罗斯&#34;不太可能把它当作一个地方......

所有这一切, std :: string和UTF-8都是一个脆弱的混合。很容易忘记length()没有给出字形的数量,substr()可能会导致无效的字节序列,toupper()并不能真正起作用对于一切,以及许多其他类似的陷阱。我建议使用ICUicu::UnicodeString提供{{1}}&#34;知道&#34;关于所有这些事情。