gpt4 book ai didi

c++ - ifstream 忽略空格和换行 - 为什么?

转载 作者:行者123 更新时间:2023-12-04 19:03:52 26 4
gpt4 key购买 nike

所以我正在编写一个简单的程序,只是想了解它为什么忽略空格(它将它们视为新行)以及为什么它不考虑新行。

语言:C++

平台:Kubuntu 13.04

编译器:g++

代码:

 unsigned int lines;
string line_content;
ifstream r_tftpd_hpa("/etc/default/tftpd-hpa"); // open file

// test for errors
if ( r_tftpd_hpa.fail() ) {
cerr << "Error opening file: \"/etc/default/tftpd-hpa\"" << endl;
exit(1);
}

// loop through file until end
while ( !r_tftpd_hpa.eof() ) {
r_tftpd_hpa >> line_content;
lines++;

// I also tried with \n
if ( line_content[0] == ' ' ) { // my failed attempt at catching spaces
cout << endl << "Found empty line: " << lines << endl;
}

cout << "Line: " << lines << " content: " << line_content << endl;
}

输出:
 Line: 1 content: #
Line: 2 content: /etc/default/tftpd-hpa
Line: 3 content: TFTP_USERNAME="tftp"
Line: 4 content: TFTP_DIRECTORY="/var/lib/tftpboot"
Line: 5 content: TFTP_ADDRESS="0.0.0.0:69"
Line: 6 content: TFTP_OPTIONS="--secure"
Line: 7 content: TFTP_OPTIONS="--secure"

文件本身:
 # /etc/default/tftpd-hpa

TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/var/lib/tftpboot"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure"

该文件由 6 行组成,但它似乎认为它是 7。它计算 # 之后的空间在第 1 行作为新行并忽略原始文件中第 2 行的空格。它还打印行 6 and 7好像有两个同一行,没有。

知道这里发生了什么吗?我们如何处理空格和换行符?

最佳答案

operator >>吃掉任何空格(换行符、制表符、空格)。如果需要统计行数,可以使用 getline 功能。

#include <cassert>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
unsigned lines = 0;
string line_content;

ifstream r_tftpd_hpa ("tftpd-hpa");
assert(r_tftpd_hpa);

while ( getline(r_tftpd_hpa, line_content) ) {
lines++;

if ( line_content[0] == ' ' ) { // my failed attempt at catching spaces
cout << endl << "Found empty line: " << lines << endl;
}

cout << "Line: " << lines << " content: " << line_content << endl;
}

return 0;
}

给我:
Line: 1 content: # /etc/default/tftpd-hpa
Line: 2 content:
Line: 3 content: TFTP_USERNAME="tftp"
Line: 4 content: TFTP_DIRECTORY="/var/lib/tftpboot"
Line: 5 content: TFTP_ADDRESS="0.0.0.0:69"
Line: 6 content: TFTP_OPTIONS="--secure"

关于c++ - ifstream 忽略空格和换行 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16498774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com