C++ ifstream 只读一个单词的数量
C++ ifstream read only number of a word
所以我想从.txt文件中读取数字作为整数。
文件.txt:
hello 123-abc
world 456-def
当前代码:
int number;
ifstream file("file.txt");
while (!file.eof())
{
file >> number; //123, 456
}
现在这显然不起作用,我一直在尝试解决这个问题"一段时间",但我就是无法解决这个问题。
有很多方法可以做到这一点。 您尝试过的方法不起作用,因为流中的读取位置没有类似数字的东西。 因此,输入将失败,并且将设置流的故障位。 您将永远循环,因为您只是在测试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 != ' '; 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;
}
这有点笨拙,它还会检测您可能不想要的负面因素。 但这是一种简单的方法。 如果提取了任何字符,next
指针将与p
不同。 否则,函数将失败。 然后p
递增 1 并再次搜索。 它看起来像多项式搜索,但它是线性的。
我从 C++17 开始使用std::optional
,但我是在 C++14 编译器上进行测试。 这是为了方便。 您可以在没有它的情况下编写函数。
现场例子在这里。
解决此类问题的更灵活方法是使用正则表达式。 在这种情况下,您只需要一个简单的数字正则表达式搜索。 以下内容将仅查找正整数,但您也可以使用此类型的模式来查找复杂数据。 不要忘记包含标题<regex>
:
std::experimental::optional<int> find_int_regex( const std::string & s )
{
static const std::regex r( "(\d+)" );
std::smatch match;
if( std::regex_search( s.begin(), s.end(), match, r ) )
{
return std::stoi( match[1] );
}
return {};
}
现场例子在这里。
您需要检查文件是否已打开,然后获取当前行,然后解析该当前行以获取第一个数字:
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);
获取子字符串来查找下一个空格
我相信你可以弄清楚其余的,祝你好运。
逐行读取并删除所有不是数字的字符。在推到你的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));
}
或者使用std::regex_replace
删除非数字字符:
auto tmp = std::regex_replace(s, std::regex{R"raw([^d]+(d+).+)raw"}, "$1");
numbers.push_back(std::stoi(tmp));
现场示例
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 计算单词中的音节数,但考虑到单词中彼此相邻的任何元音都算作一个音节
- 如何检查流中文件的下一个单词是否为 alpha?
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 计算一个单词在映射中出现的次数 - 使用 transform() - 调用不匹配
- 如何制作一个程序,它使用特定单词加密和解密消息?
- 创建一个函数,返回给定单词在C++中的频率
- 如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
- 输入一个字符串并将其除以单词
- 我有一个字符串变量单词= "APA"
- 将字符串中的单个单词替换为另一个单词
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 如何将行的第一个单词作为一个变量,将行的其余部分作为另一个变量进行归档/存储
- 给定一个字符串,只要您看到单词"ant"替换到字符串中,单词就会"termite"
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- 检查一个文本文件中的单词是否在另一个文本文件 (C++) 中
- 如何插入一个单词并将字母放在2D数组中的不同索引中