我想从文件中读取这样的输入
球体 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]
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我不知道将输入多少个整数,这就是我想在新行处停止的原因。我用 getline 做到了,然后分割线,但他们告诉我只能用 >> 运算符来完成。
注意:我不能使用std::stringor 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(); }
}
}
Run Code Online (Sandbox Code Playgroud)
我个人的猜测是,作业要求将值读入char数组,然后使用atoi()or进行转换strol()。我认为这对练习来说是一个无聊的解决方案。
(*)永远不要,即使在示例代码中,也不要在不设置最大允许大小的情况下将格式化输入运算符与数组一起使用char!可以通过设置流的 来设置大小,例如使用操纵器。如果在对数组使用格式化输入运算符时使用is ,则会读取任意数量的非空白字符。这很容易使数组溢出并成为安全问题!本质上,这是拼写 C 的 C++ 方式(现已从 C 和 C++ 标准库中删除)。array width()std::setw(sizeof(array))width()0chargets()
| 归档时间: |
|
| 查看次数: |
3606 次 |
| 最近记录: |