繁体   English   中英

getline 似乎无法正常工作

[英]getline seems to not working correctly

请告诉我我在这里做错了什么。 我想做的是:
1.有四个数字的txt文件,每个数字有15位:

std::ifstream file("numbers.txt",std::ios::binary);

我正在尝试将这些数字读入我的数组:

  char num[4][15];

我在想我正在做的是:只要你没有到达文件末尾,就将每一行(最多 15 个字符,以 '\n' 结尾)写入 num[lines]。 但这有点行不通。 首先它只正确读取第一个数字,rest 只是“”(空字符串),其次 file.eof() 似乎也不能正常工作。 在我在此代码下方显示的 txt 文件中,我达到了等于 156 的行数。这是怎么回事?

                for (unsigned lines = 0; !file.eof(); ++lines)
                {
                    file.getline(num[lines],15,'\n');  
                }

所以整个“例程”看起来是这样的:

int main()
{
std::ifstream file("numbers.txt",std::ios::binary);

char numbers[4][15];

            for (unsigned lines = 0; !file.eof(); ++lines)
            {
                file.getline(numbers[lines],15,'\n');// sizeof(numbers[0])
            }
}

这是我的 txt 文件的内容:

111111111111111
222222222222222
333333333333333
444444444444444

附言
我正在使用 VS2010 sp1

不要使用 eof() function:读取行的规范方法是:

while( getline( cin, line ) ) {
    // do something with line
}

file.getline()提取 14 个字符,填入num[0][0].. num[0][13] 然后它在num[0][14]中存储一个'\0'并在file中设置failbit ,因为这是在缓冲区已满但未达到终止字符时所做的事情。

由于设置了失败位,因此进一步尝试调用file.getline()什么也不做。

.file.eof()的测试返回 true,因为未设置 eofbit。

编辑:举一个工作示例,当然,最好是使用字符串,但是要填写您的 char 数组,您可以这样做:

#include <iostream>
#include <fstream>
int main()
{
    std::ifstream file("numbers.txt"); // not binary!
    char numbers[4][16]={}; // 16 to fit 15 chars and the '\0'
    for (unsigned lines = 0;
         lines < 4 && file.getline(numbers[lines], 16);
         ++lines)
    {
        std::cout << "numbers[" << lines << "] = " << numbers[lines] << '\n';
    }
}

在 Visual Studio 2010 SP1 上测试

根据ifstream doc ,在读取 n-1 个字符或找到 delim 符号后停止读取:第一次读取只需要 14 个字节。

它读取字节:'1'(字符)是 0x41:您的缓冲区将填充 0x41 而不是 1,如您所料,最后一个字符将为 0(c 字符串的结尾)

旁注,您的代码不会检查数组之外的行是否 go 。

使用 getline 假设您期待文本并且以二进制模式打开文件:对我来说似乎是错误的。

将其更改为以下内容:

#include <cstring>

int main()
{
    //no need to use std::ios_base::binary since it's ASCII data
    std::ifstream file("numbers.txt");

    //allocate one more position in array for the NULL terminator
    char numbers[4][16];

    //you only have 4 lines, so don't use EOF since that will cause an extra read
    //which will then cause and extra loop, causing undefined behavior
    for (unsigned lines = 0; lines < 4; ++lines)
    {
        //copy into your buffer that also includes space for a terminating null
        //placing in if-statement checks for the failbit of ifstream
        if (!file.getline(numbers[lines], 16,'\n'))
        {
            //make sure to place a terminating NULL in empty string
            //since the read failed
            numbers[lines][0] = '\0';
        }
    }

}

看起来第一个 like 末尾的 '\n' 没有被考虑,而是保留在缓冲区中。 所以在下一个getline()中它被读取。

尝试在每个 getline() 之后添加一个 file.get()。

如果一个 file.get() 不起作用,请尝试两个,因为在 Windows 默认文件编码下,该行以'\n\r\'(或'\r\n',我永远不知道:)结尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM