【发布时间】:2013-08-23 08:24:32
【问题描述】:
我试图将整个 .txt 文件复制到 char 数组中。我的代码有效,但它忽略了空格。因此,例如,如果我的 .txt 文件读取“我喜欢派”并将其复制到 myArray,如果我使用 for 循环计算我的数组,我会得到“ILikePie”
这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
int arraysize = 100000;
char myArray[arraysize];
char current_char;
int num_characters = 0;
int i = 0;
ifstream myfile ("FileReadExample.cpp");
if (myfile.is_open())
{
while ( !myfile.eof())
{
myfile >> myArray[i];
i++;
num_characters ++;
}
for (int i = 0; i <= num_characters; i++)
{
cout << myArray[i];
}
system("pause");
}
有什么建议吗? :/
【问题讨论】:
-
arraysize 应该是 const。
-
!myfile.eof()的使用不正确。即使您想阅读单词,而不是所有字符,您也在使用myfile >> myArray[i]的结果而没有验证它是否成功,这是不正确的。如果您想阅读所有字符,那么while ( myfile.get( myArray[i] ) ) ++i;可以工作(但您仍然需要边界检查)。但 Nemanja 的回答要好得多。