我想从文件中读取这样的输入
sphere 3 2 3 4
pyramid 2 3 4 12 3 5 6 7 3 2 4 1 2 3
rectangle 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()
转换它们>。我认为这将是一个无聊的练习解决方案。
(*) 从不,即使在示例代码中,也不要在 char
数组 array
中使用格式化输入运算符 without 还设置了最大允许大小!可以通过设置流的 width()
来设置大小,例如,使用操纵器 std::setw(sizeof(array))
。如果在对 char
数组使用格式化输入运算符时 width()
为 0
,则会读取任意数量的非空白字符。这可以很容易溢出数组并成为安全问题!本质上,这是拼写 C 的 gets()
的 C++ 方式(现在已从 C 和 C++ 标准库中删除)。
关于C++如何读取流直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689997/