C++ 读取文件时出现分段错误
我正在尝试打印文件的最后10行。下面是我的代码,但由于fscanf,它给出了一个分段错误。在使用gdb运行时,错误读取:vfscanf.c:没有这样的文件或目录C++ 读取文件时出现分段错误,c++,file,segmentation-fault,C++,File,Segmentation Fault,我正在尝试打印文件的最后10行。下面是我的代码,但由于fscanf,它给出了一个分段错误。在使用gdb运行时,错误读取:vfscanf.c:没有这样的文件或目录 #include <iostream> #include <stdio.h> #include <string> using namespace std; int main() { FILE *fp = fopen("microfile.txt","r"); char *c[10];
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
FILE *fp = fopen("microfile.txt","r");
char *c[10];
int idx = 0;
cout<<fp<<"\n";
while(!feof(fp))
{
if(idx<10)
{
fscanf(fp,"%s",c[idx]);
idx++;
}
else if(idx==10)
{
for(int i=0;i<idx-1;i++)
{
c[i] = c[i+1];
}
fscanf(fp,"%s",c[idx-1]);
}
}
int i=0;
while(i<10)
{
cout<<c[i]<<"\n";
i++;
}
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
文件*fp=fopen(“microfile.txt”、“r”);
char*c[10];
int-idx=0;
cout问题的根源在于这一行上有一个指针数组:
char* c[10];
稍后在程序中,您尝试将字符值分配给这些指针。可能您的意思是只分配一个字符数组:
char c[10];
此外,建议使用标准库。尝试使用std::string
和标准流,您的程序可以更易于维护:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string s;
s.assign(
std::istreambuf_iterator<char>(std::ifsteam("microfile.txt").rdbuf()),
std::istreambuf_iterator<char>());
for (char c : s)
std::cout << c << std::endl;
}
#包括
#包括
#包括
int main()
{
std::字符串s;
s、 分配(
std::istreambuf_迭代器(std::ifsteam(“microfile.txt”).rdbuf(),
std::istreambuf_迭代器();
用于(字符c:s)
STD:为什么你不使用C++?你知道你的代码是几乎C吗?唯一的C++东西是CUT。你应该学会如何在C++中做等价的操作或者切换到C.<代码> [IDX] < /代码>,我不知道代码< CID[ID]的在哪里。你知道什么是动态内存分配吗?你知道什么是不确定指针吗?最后你知道你不是在做前一个,并且使用一个10个后面的数组,每个都是一个代码的目标?fSCANF
,从而调用未定义的行为?@ 0x499 602D2,他使用C++,或者我相当肯定地说< COD >e> #include
会吐得到处都是。如果你问OP为什么没有使用仅限C++的标准库功能,我完全同意。