c++如何读取流直到行尾
c++ how to read stream till end of line
我想从文件中读取这样的输入
球体3 2 3 4
棱锥体2 3 4 12 3 5 6 7 3 2 4 1 2 3
矩形2 3 4 1 9 12
我想做一些类似的事情
char name[64];
int arr[12];
ifstream file (..);
while(file)
{
file >> name;
while( //reach end of line)
file >> arr[i]
}
正如你们所看到的,我不知道会输入多少个整数,这就是为什么我想停在新行。我用getline做了这件事,然后拆分了行,但他们告诉我只能用>>运算符。
注意:我不能使用std::string
或std::vector
。
简单的版本是使用类似于std::ws
的操纵器,但不是在遇到换行符时跳过所有空白设置std::ios_base::failbit
。然后,这个操纵器将被用来隐式跳过空白,而不是跳过换行符。例如(代码没有经过测试,但我认为这样删除了错误和编译错误的东西应该可以工作):
std::istream& my_ws(std::istream& in) {
std::istream::sentry kerberos(in);
while (isspace(in.peek())) {
if (in.get() == 'n') {
in.setstate(std::ios_base::failbit);
}
}
return in;
}
// ...
char name[64];
int array[12];
while (in >> std::setw(sizeof(name)) >> name) { // see (*) below
int* it = std::begin(array), end = std::end(array);
while (it != end && in >> my_ws >> *it) {
++it;
}
if (it != end && in) { deal_with_the_array_being_full(); }
else {
do_something_with_the_data(std::begin(array), it);
if (!in.eof()) { in.clear(); }
}
}
我个人的猜测是,任务要求将值读取到char
数组中,然后使用atoi()
或strol()
进行转换。我认为这将是一个无聊的练习解决方案。
(*)Never,即使在exmaple代码中,也不要将格式化的输入运算符与char
数组array
一起使用,也不要设置允许的最大大小!可以通过设置流的width()
来设置大小,例如使用操纵器std::setw(sizeof(array))
。如果在使用具有char
数组的格式化输入运算符时width()
是0
,则读取任意数量的非空白字符。这会很容易溢出数组并成为安全问题!从本质上讲,这是C的gets()
的C++拼写方式(现在已从C和C++标准库中删除)。
我想您可以使用peek方法:
while (file)
{
file >> name;
int i = 0;
while(file.peek() != 'n' && file.peek() != EOF) {
file >> arr[i++];
}
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- C++ 读取文件读取文件不正确
- 如何让我的CSV文件读取器读取C 中的不同类型
- 从文件读取时读取访问冲突
- 从文件读取不读取字符串流
- 读取错误-读取时无限
- 以较小、更频繁的读取或较大的读取方式读取输入
- 从内存到硬盘驱动器(C/ c++)读取和读取整个数组
- FFMPEG自定义读取功能读取所有数据
- 对从文件中读取和读取结构中的结构感到困惑
- 读取、读取、获取和获取行之间有什么区别?