为什么 ifstream 在读取混合数据时失败?
Why is ifstream failing when reading mixed data?
我有一个包含单词和整数的文本文件。任务是只从中读取整数而忽略单词。这是此类文件的示例:
seven 7
我声明了一个 int 变量并尝试将 ifstream 读入其中(回应 ifstream 的状态):
#include <iostream>
#include <fstream>
int main() {
int num = -1;
std::ifstream ifs("file.in");
std::cout << ifs << std::endl;
ifs >> num;
std::cout << ifs << std::endl;
if ( ifs.fail() )
ifs.clear();
std::cout << ifs << std::endl;
ifs >> num;
std::cout << ifs << std::endl;
std::cout << num << std::endl;
return 0;
}
我得到一个输出:
1
0
1
0
-1
很明显,'ifs' 在尝试将单词读入 int 变量时失败了。我的问题是为什么清除后第二次失败?
第一次失败没有提高流位置,所以第二次失败再次尝试,结果完全相同。您需要跳过不需要的单词,将其读入字符串或使用 ignore
.
我有一个包含单词和整数的文本文件。任务是只从中读取整数而忽略单词。这是此类文件的示例:
seven 7
我声明了一个 int 变量并尝试将 ifstream 读入其中(回应 ifstream 的状态):
#include <iostream>
#include <fstream>
int main() {
int num = -1;
std::ifstream ifs("file.in");
std::cout << ifs << std::endl;
ifs >> num;
std::cout << ifs << std::endl;
if ( ifs.fail() )
ifs.clear();
std::cout << ifs << std::endl;
ifs >> num;
std::cout << ifs << std::endl;
std::cout << num << std::endl;
return 0;
}
我得到一个输出:
1
0
1
0
-1
很明显,'ifs' 在尝试将单词读入 int 变量时失败了。我的问题是为什么清除后第二次失败?
第一次失败没有提高流位置,所以第二次失败再次尝试,结果完全相同。您需要跳过不需要的单词,将其读入字符串或使用 ignore
.