2016-11-21 95 views
-1

我一直在编写代码来使用C++将文件读入字符数组。我试图跳过空白字符,但我在我的输出数组中获取空​​格和换行符。在C++中将文件读入字符数组

这是标签声明为字符数组的类中的函数。

 //Read the label file 
80  this->label = new char[vert_count+1]; 
81  std::ifstream file1; 
82  file1.open(label_file); 
83  if(file1 != NULL) 
84  { 
85   char temp; int i = 0; 
86   std::cout << "Label file opened successfully" << std::endl; 
87   if(i< vert_count) 
88   { 
89    file1.get(temp); 
90    if(temp != ' ' && temp != '\n'&& temp != '\t') 
91    { 
92     label[i] = temp; 
93     i++; 
94    } 
95   } 
96   label[vert_count] = '\0';//putting null character to terminate 
97   file1.close(); 
98  } 
99  else   
100   std::cout << "label file cannot be opened\n"; 
101  for (int i = 0; i< vert_count; i++) 
102   std::cout <<label[i]; 

我的输入文件格式如下图所示

a 
b 
c 
d 
e 
f 
1 
2 
H 
M 
O 

我得到的输出是在启动字符的一束,然后空格,只有新的生产线。

+0

'i'没有在你的榜样初始化。不要以为它会是0. –

+0

它看起来像我只是从文件中读取一行。没有循环。 –

+1

@JimBaldwin更少,1个字符。 –

回答

3

我认为你的意思(在线87):

while (i < vert_count)