簡體   English   中英

C ++ ifstream只讀單詞數

[英]C++ ifstream read only number of a word

所以我想從.txt文件中讀取數字作為整數。

file.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 != '\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;
}

這有點笨拙,並且還會檢測出您可能不需要的底片。 但這是一種簡單的方法。 如果提取了任何字符,則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);獲取子字符串來查找下一個空格(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));

現場例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM