当我一次读取一个字符的文本文件,然后将该字符发送到一个字符串(这是一个字符数组)它似乎工作,输出显示正确,但然后崩溃。为什么?C++通过char将Char文件读入字符串;崩溃
第二个问题:它似乎没有为字符串(这是一个字符数组)添加空格。为什么?
#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