我在格式化 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;
}
uj5u.com熱心網友回復:
假設您的目標不是保持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
現場示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441141.html
