【问题标题】:Reading a file into character array in C++在 C++ 中将文件读入字符数组
【发布时间】:2016-11-21 01:24:30
【问题描述】:

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

这是类中的一个函数,其中 label 声明为字符数组。

        //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

我得到的输出是开始时的一堆字符,然后是空格和换行符。

【问题讨论】:

  • i 在您的示例中未初始化。不要假设它会是 0。
  • 在我看来你只是从文件中读取一行。没有循环。
  • @JimBaldwin 甚至更少,1 个字符。
  • 你可以有一个像 int i = 0, char x; 这样的循环。 while(file1.good()) { 文件 >> x; if(x == ' ') ;//什么都不做 { label[i] = x; } }
  • @JimBaldwin 我现在正在打败自己。谢谢老兄

标签: c++ arrays file


【解决方案1】:

我想你的意思是(在第 87 行):

while (i < vert_count)

【讨论】:

    猜你喜欢
    • 2012-11-08
    • 1970-01-01
    • 2017-05-16
    • 2020-07-08
    • 2011-08-01
    • 2011-03-18
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多