テキストファイルを一度に1文字ずつ読み込んで文字列(文字の配列)に送信すると、出力が正常に表示されているように見えますが、クラッシュします。どうして?C++ CharによるファイルCharの文字列への読み込み。クラッシュ
2番目の質問:文字列(文字の配列)に空白を追加するようには表示されません。どうして?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cctype>
using namespace std;
int main()
{
int SIZE = 0;
char text;
string textArray;
fstream inFile("text.txt"); //opens text.txt
//checks if file was opened
if (!inFile)
{
cout << "Error opening the file.\n";
return 0;
}
//reads each character then adds the character to the array
while (inFile >> text)
{
//if you coment out line 46 and 47 the program wont crash
textArray[SIZE] = text; //comment out // doesnt add white spaces
cout << textArray[SIZE]; //comment out // the output form this is the text.txt but no white spaces
SIZE++;
}
inFile.close(); //closes text.txt
cout << SIZE; //output the size of the array
return 0;
}
文字列が*ゼロ*長で作成されているため、存在しない '[]'を使用して文字列の文字を上書きしています。 'push_back()'を使用してください – Galik
ありがとう、それはベクトルと関係がありますか?私はベクトルを認識していますが、これは初心者クラスであり、ベクトルはカバーされません。ベクトルなしでこれを行うにはとにかくありますか? – Edix
'std :: string'と同じ' std :: vector'と同じです。あなたはチュートリアルを見つけて、それでも良い本を手に入れ、それを実践しなければなりません。 – Galik