读取文件和使用getline进行标准输入的结果不同
different result from file reading and standard input with getline
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*";
现在都被接受了
相关文章:
- 从标准输入读取文件后读取用户输入
- 如何从标准输入中检测格式化输入错误?
- C++ - 标准输入环路
- 快速读取标准输入缓冲区,无需检查
- 将标准输入中的双精度存储在矢量中
- 如何将 getline 与标准输入一起使用?
- 从 C++ 中的标准输入迭代读取字节
- C++计算标准输入的字数
- 如何从 c++ 中的给定标准输入中获取每个字符的偏移量?
- 为什么此代码从标准输入中少一个输入?
- 如何在C++中从标准输入中获取变量输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 如何在execl中使用标准输入'<'?
- 如何在 eclipse 中将标准输入从控制台更改为另一个程序
- 流对象来表示文件输入,然后是标准输入?
- 标准输入输出操作如何C++完成
- 从标准输入读取时zmq_poll不侦听信号
- 执行控制台程序,写入标准输入并使用管道读取结果
- 读取文件和使用getline进行标准输入的结果不同