c++ - 搜索行尾的段错误

标签 c++

我正在编写代码来计算文件的行数和字符数。

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

相关文章:

c++ - 为什么只有 static_cast 能够返回请求类型的新对象?

c++ - 为什么 OpenCV 构造函数在 iPhone 5 而不是 iPhone 6/iPad 上工作?

c++ - 测量耗时,将开始时间存储为原始类型

c++ - 我可以在不安装 Visual Studio 的情况下使用英特尔 C++ 编译器 [在 Windows 上]

c++ - 如何更正警告 : cast to pointer from integer of different size [-Wint-to-pointer-cast]

c++ - 如何在 Windows 上将 BYTE 数组映射为 FILE *

c++ - spdlog 错误 : "don' t know how to format the type, 包括 fmt/ostream.h(如果它提供了应使用的运算符 <<)”

c++读取JSON场景文件

c++ - 生成没有 stub 的 WSDL 请求/响应

c++ - opencv 中的 StereoBM 类是否对输入图像或帧进行校正?