c++如何读取流直到行尾

c++ how to read stream till end of line

本文关键字:读取 何读取 c++      更新时间:2023-10-16

我想从文件中读取这样的输入

球体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::stringstd::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++];
}
}