【发布时间】: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 我现在正在打败自己。谢谢老兄