当我对这个文件使用 a.out 时,为什么我总是收到 zsh: segmentation fault 错误?
Why do I keep getting a zsh: segmentation fault error when I use a.out for this file?
C++ 文件 io 的新功能。我最初正在编写一个基本程序来简单地从文件中删除注释。如果前两个字符是//,那么我基本上需要跳过并打印文本文件中的以下行。我的输出文件和输入文件都与我的 CPP 文件在同一个文件夹中,所以我不确定为什么我总是在这里收到错误。
#include <iostream>
#include <stream>
using namespace std;
int main() {
ifstream in_stream("HW2Test.txt");
ofstream output_stream("HW2output.txt");
string result[100];
int i;
while(!in_stream.eof()) {
in_stream>>result[i];
i++;
}
for(int j = 0; j<i; j++) {
if((result[j][0]=='/')&&(result[j][0]=='/')) {
output_stream<<result[j+1];
}
}
output_stream.close();
in_stream.close();
return 0;
}
您的变量 int i
未初始化,因此 in_stream>>result[i]
会产生未定义的行为。
改用 int i=0
(并在写入缓冲区之前检查是否 i < 100
)。
C++ 文件 io 的新功能。我最初正在编写一个基本程序来简单地从文件中删除注释。如果前两个字符是//,那么我基本上需要跳过并打印文本文件中的以下行。我的输出文件和输入文件都与我的 CPP 文件在同一个文件夹中,所以我不确定为什么我总是在这里收到错误。
#include <iostream>
#include <stream>
using namespace std;
int main() {
ifstream in_stream("HW2Test.txt");
ofstream output_stream("HW2output.txt");
string result[100];
int i;
while(!in_stream.eof()) {
in_stream>>result[i];
i++;
}
for(int j = 0; j<i; j++) {
if((result[j][0]=='/')&&(result[j][0]=='/')) {
output_stream<<result[j+1];
}
}
output_stream.close();
in_stream.close();
return 0;
}
您的变量 int i
未初始化,因此 in_stream>>result[i]
会产生未定义的行为。
改用 int i=0
(并在写入缓冲区之前检查是否 i < 100
)。