1

最初にキリル文字でファイルを読み取り、次にランダムな数の行をランダムに選択して、変更したテキストを別のファイルに書き込む必要があります。ラテン文字には問題ありませんが、ゴミが出るため、キリル文字に問題が発生します。だから、これが私がそのことをやろうとした方法です。

言う、ファイルinput.txt

ааааааа
ббббббб
ввввввв

私はそれを読んで、すべての行をベクトルに入れる必要があります:

vector<wstring> inputVector;
wstring inputString, result;
wifstream inputStream;
inputStream.open("input.txt");
while(!inputStream.eof())
{
    getline(inputStream, inputString);              
    inputVector.push_back(inputString);
}
inputStream.close();    

srand(time(NULL));
int numLines = rand() % inputVector.size();
for(int i = 0; i < numLines; i++)
{
    int randomLine = rand() % inputVector.size();
    result += inputVector[randomLine];
}

wofstream resultStream;
resultStream.open("result.txt");
resultStream << result;
resultStream.close();

では、シンボルだけでなく、読みやすいものを生成するために、キリル文字をどのように使用できますか?

4

2 に答える 2

2

■aaaaaaa1♦1♦1♦1♦1♦1♦1♦2♦2♦2♦2♦2♦2♦2♦のようなものがコンソールに印刷されているのを見たのでinput.txt、UTF-16でエンコードされているように見えますエンコーディング、おそらくUTF-16 LE+ BOM。ファイルのエンコーディングをUTF-8に変更すると、元のコードを使用できます。

UTF-8を使用する理由は、ファイルストリームのchar型に関係なく、basic_fstream基礎となるオブジェクトをbasic_filebuf使用して、オブジェクトのストリームをchar型のオブジェクトのストリームとの間codecvtで変換するためcharです。つまり、読み取り時にcharは、ファイルから読み取られたwchar_tストリームがストリームに変換されますが、書き込み時には、wchar_tストリームがストリームに変換さcharれてから、ファイルに書き込まれます。の場合std::wifstreamcodecvtオブジェクトは標準のインスタンスであり、std::codecvt<wchar_t, char, mbstate_t>通常はUTF-8をUCS-16に変換します。

次のMSDNドキュメントページでbasic_filebuf説明されているように:

basic_filebuf型のオブジェクトは、型パラメーターElemで指定されたchar_typeに関係なく、char*型の内部バッファーを使用して作成されます。これは、Unicode文字列(wchar_t文字を含む)が内部バッファに書き込まれる前にANSI文字列(char文字を含む)に変換されることを意味します。

同様に、Unicode文字列(文字を含むwchar_t)を読み取る場合basic_filebuf、はファイルから読み取られたANSI文字列を、wchar_t返される文字列getlineおよびその他の読み取り操作に変換します。

のエンコーディングinput.txtをUTF-8に変更すると、元のプログラムが正しく機能するはずです。

参考までに、これは私にとってはうまくいきます:

#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    using namespace std;

    vector<wstring> inputVector;
    wstring inputString, result;
    wifstream inputStream;
    inputStream.open("input.txt");
    while(!inputStream.eof())
    {
        getline(inputStream, inputString);
        inputVector.push_back(inputString);
    }
    inputStream.close();

    srand(time(NULL));
    int numLines = rand() % inputVector.size();
    for(int i = 0; i < numLines; i++)
    {
        int randomLine = rand() % inputVector.size();
        result += inputVector[randomLine];
    }

    wofstream resultStream;
    resultStream.open("result.txt");
    resultStream << result;
    resultStream.close();

    return EXIT_SUCCESS;
}

のエンコーディングresult.txtもUTF-8(通常)になることに注意してください。

于 2011-09-23T12:36:14.273 に答える
1

なぜ使用するのですか?ファイルが(システムに依存する)ワイド文字wifstreamのシーケンスで構成されていると確信していますか?ほぼ確実にそうではありません。(特に、システムのワイド文字セットが実際にはC ++プログラムの範囲外で明確ではないためです)。

代わりに、入力バイトストリームをそのまま読み取り、それに応じてエコーします。

std::ifstream infile(thefile);
std::string line;
std::vector<std::string> input;

while (std::getline(infile, line))   // like this!!
{
  input.push_back(line);
}

// etc.
于 2011-09-22T22:46:47.023 に答える