簡體   English   中英

從帶有字母和空格的文本文件中讀取數字

[英]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

這是所需的 output:

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到 output 值就非常簡單了:

#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 << " ";
    }
}

Output:

87 98.5 4 9 0 94.3 98.4 84 

實例

暫無
暫無

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

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