从带有字母和空格的文本文件中读取数字

Reading numbers from a text file with letters and whitespace

我在格式化 C++ 作业时遇到问题。我正在处理文件 I/O 作业,我有一个包含字母、数字和空格的文本文件。我希望我的程序从文本文件中读取数字并以与文本文件相同的格式显示。现在,我的代码正在输出数字,但作为一行而不是数字值。

这是文本文件:

dsfj  kdf     87  98.5 4vb
jfkd 9            jfkds000    94.3hjf
       98.4    jd84.    kfd

这是所需的输出:

We found the following magic numbers in test2.txt:
87 98.5 4 9 0 94.3 98.4 84 

这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    char ans;
   
    cout << "Welcome to Number Finder!\n";
    cout << "============================\n";
    do{
        char in_file_name[20];
        char c;
        ifstream in_stream;
        
        cout << "Which file do you want us to find numbers at?\n";
        cin >> in_file_name;
        cout << endl;
        cout << "We found the follow magic numbers in " << in_file_name << ": \n";

        in_stream.open(in_file_name);
        if(in_stream.fail()){
            cout << in_file_name << " is not found.\n";
        }
        in_stream.get(c);
        while (!in_stream.eof()){
            if(isdigit(c)){
                cout << fixed;
                cout.precision(2);
                cout << c << " ";
              }
             in_stream.get(c);
         }
        double num;
        while(in_stream >> num){
            cout << fixed;
            cout.precision(2);
            cout << num << " ";
        }
        cout << endl;
        cout << "-----";
        cout << endl;
        cout << "Do you want to process another file? \n";
        cin >> ans;
        in_stream.close();
    } while (ans== 'Y' || ans=='y');
    cout << "Thank you for using the Number Finder! Bye for now!";
    return 0;
}

假设您的目标不是保持文件中 double 值的准确性,一种方法是将该行作为字符串读入,并删除所有非数字字符, 除了 空格和 ..

完成后,使用 std::istringstream 输出值就非常简单了:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>

int main()
{
    std::string line;
    // Read the entire line
    while (std::getline(std::cin, line))
    {
        // erase all non-digits, except for whitespace and the '.' 
        line.erase(std::remove_if(line.begin(), line.end(), 
                   [](char ch) { return !std::isdigit(ch) && !std::isspace(ch) && ch != '.'; }), line.end());

        // Now use the resulting line and read in the values
        std::istringstream strm(line);
        double oneValue;
        while (strm >> oneValue)
           std::cout << oneValue << " ";
    }
}

输出:

87 98.5 4 9 0 94.3 98.4 84 

Live Example