读取文件和使用getline进行标准输入的结果不同

different result from file reading and standard input with getline

本文关键字:标准输入 结果 文件 getline 读取      更新时间:2023-10-16
bool validateCurrencyLine(string line){
    cout << "TESTING LINE : " << line << endl;
    string pattern = "[ ]*([A-Z]{3}) ([0-9]+)([ ]*|,[0-9]+[ ]*)";
    boost::regex expr{pattern};
    return boost::regex_match(line,expr);
}
int main()
{
    string line;
    while(getline(cin,line)){
        cout << validateCurrencyLine(line) << endl;
    }
    return 0;
}

test文件内容如下:

IDK 3453443

现在,当我使用./a.out < test启动程序时,结果是

TESTING LINE : IDK 3453443
0
TESTING LINE : 
0

我的假设是打印第二行,因为测试文件的第一行实际上是

IDK 3453443 + enter

但真正的问题是,当我像这样启动它:./a.out并输入"IDK 3453443"并按enter键。结果是:

TESTING LINE : IDK 3453443
1

你知道为什么这两个结果不同吗?

确实行尾是罪魁祸首。

在十六进制编辑器中查看该文件,您将发现0d 0a行结束符(Windows或CRLF),其中代码期望UNIX行结束符(仅LF)。

现场观看:

Live On Coliru

你可以通过"吃掉"末尾的所有空白来解决这个问题:

Live On Coliru

std::string pattern = "[ ]*([A-Z]{3}) ([0-9]+)(,[0-9]+)?\s*";

现在都被接受了