C++ C++;ifstream只读字数
所以我想把.txt文件中的数字读作整数 file.txt:C++ C++;ifstream只读字数,c++,fstream,ifstream,C++,Fstream,Ifstream,所以我想把.txt文件中的数字读作整数 file.txt: hello 123-abc world 456-def 当前代码: int number; ifstream file("file.txt"); while (!file.eof()) { file >> number; //123, 456 } 现在,这显然不起作用,我已经尝试解决这个问题“一段时间”,但我无法回避这个问题。您需要检查文件是否打开,然后获取当前行,然后解析当前行以获取第一个数字: std::st
hello 123-abc
world 456-def
当前代码:
int number;
ifstream file("file.txt");
while (!file.eof())
{
file >> number; //123, 456
}
现在,这显然不起作用,我已经尝试解决这个问题“一段时间”,但我无法回避这个问题。您需要检查文件是否打开,然后获取当前行,然后解析当前行以获取第一个数字:
std::string currentLine = "";
std::string numbers = "";
ifstream file("file.txt");
if(file.is_open())
{
while(std::getline(file, currentLine))
{
int index = currentLine.find_first_of(' '); // look for the first space
numbers = currentLine.substr(index + 1, xyz);
}
}
xyz是数字的长度(在本例中为3,如果始终不变),或者您可以通过从(index,currentLine.back()-index)获取子字符串来查找下一个空格代码>
我相信你能解决剩下的问题,祝你好运。有很多方法可以做到这一点。您尝试的方法不起作用,因为流中的读取位置没有类似数字的东西。因此,输入将失败,流的失败位将被设置。您将永远循环,因为您只测试eof。了解更多信息
一种简单的方法是一次读取一行,然后利用std::strtol的第二个参数搜索第一个数字:
#include <iostream>
#include <string>
#include <experimental/optional>
std::experimental::optional<int> find_int_strtol( const std::string & s )
{
for( const char *p = s.c_str(); *p != '\0'; p++ )
{
char *next;
int value = std::strtol( p, &next, 10 );
if( next != p ) {
return value;
}
}
return {};
}
int main()
{
for( std::string line; std::getline( std::cin, line ); )
{
auto n = find_int_strtol( line );
if( n )
{
std::cout << "Got " << n.value() << " in " << line << std::endl;
}
}
return 0;
}
活生生的例子。逐行阅读并删除所有非数字字符。在推到您的std::vector
之前,用std::stoi
完成
std::ifstream file{"file.txt"};
std::vector<int> numbers;
for (std::string s; std::getline(file, s);) {
s.erase(std::remove_if(std::begin(s), std::end(s),
[] (char c) { return !::isdigit(c); }), std::end(s));
numbers.push_back(std::stoi(s));
}
所以您想忽略任何可能不是数字的内容?试着读入字符串。然后使用正则表达式匹配字符串,并从正则表达式的匹配组之一获取数字。困惑了吗?:-)无可否认,正则表达式比其他类型的读取更简单,因为像123
这样的连续字符序列,尽管stoi
通常会从字符串的前面提取尽可能多的整数,因此YMMVwhile(!file.eof())你知道这个数字前面总是有空格吗?我不认为在这个例子中这是一个标准,因为他显示了两行相同的行,但只要在数字前后的文件中有空格,这个概念就是一样的。获取一个子字符串,看看它是否可以转换为int,如果不能,则尝试下一个子字符串,依此类推。
std::ifstream file{"file.txt"};
std::vector<int> numbers;
for (std::string s; std::getline(file, s);) {
s.erase(std::remove_if(std::begin(s), std::end(s),
[] (char c) { return !::isdigit(c); }), std::end(s));
numbers.push_back(std::stoi(s));
}
auto tmp = std::regex_replace(s, std::regex{R"raw([^\d]+(\d+).+)raw"}, "$1");
numbers.push_back(std::stoi(tmp));