我正在编写代码来计算文件的行数和字符数。
#include <fstream>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream read(argv[1]);
char line[256];
int nLines=0, nChars=0, nTotalChars=0;
read.getline(line, 256);
while(read.good()) /
{
nChars=0;
int i=0;
while(line[i]!='\n')
{
if ((int)line[i]>32) {nChars++;}
i++;
}
nLines++;
nTotalChars= nTotalChars + nChars;
read.getline(line, 256);
}
cout << "The number of lines is "<< nLines << endl;
cout << "The number of characters is "<< nTotalChars << endl;
}
行 while(line[i]!='\n')
似乎是以下错误的原因
Segmentation fault (core dumped)
我不知道哪里出了问题。互联网告诉我,据我所知,我正在正确检查一行的结尾。
最佳答案
您的代码将找不到 '\n'
,因为它已从输入序列中丢弃。来自 getline
的文档:
The delimiting character is the newline character [...]: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s.
您应该搜索 '\0'
:
while(line[i])
{
if ((int)line[i]>32) {nChars++;}
i++;
}
关于c++ - 搜索行尾的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125943/