从文件中读取花车/字/符号,仅将存储阵列中的C中的彩车++ [英] Reading floats/words/symbols from a file and ONLY storing the floats in an array C++
本文介绍了从文件中读取花车/字/符号,仅将存储阵列中的C中的彩车++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C ++编程的问题是有人问我来自一个包含若干浮标,文字和符号读取文件(例如#%!
)。从这个文件我一定要只花车,并将其存储到一个数组中。
文本文件可能看起来像这样
11
你好
1.00
16.0
1.999
我知道如何打开该文件;它只是只抓住我挣扎彩车。
解决方案
//读取文本文件,只存储浮点值
#包括LT&;&iostream的GT;
#包括LT&;&的fstream GT;
#包括LT&;串GT;
#包括LT&;&sstream GT;使用命名空间std;诠释主(){
串线;
ifstream的MYFILE(example.txt文件);
的std ::矢量<浮球GT;采集; 如果(myfile.is_open())
{
而(函数getline(MYFILE,线))
{
如果(checkIfFloatType(线))
{
collection.push_back(性病:: STOF(线));
}
}
myfile.close();
} 否则COUT<< 无法打开文件; 返回0;
}布尔checkIfFloatType(字符串str){
的std :: istringstream ISS(STR);
浮F;
ISS>> noskipws>> F;
返回iss.eof()及&放大器; !iss.fail();
}
I have a C++ programming question that I'm asked to read from a file that contains several floats, words and symbols (e.g. # ! %
). From this file I must take only the floats and store it into an array.
The text file may look like this
11 hello 1.00 16.0 1.999
I know how to open the file; it's just grabbing ONLY the floats I'm struggling with.
解决方案
// reading a text file and storing only float values
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
std::vector<float> collection;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
if(checkIfFloatType(line))
{
collection.push_back(std::stof (line));
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
bool checkIfFloatType( string str ) {
std::istringstream iss(str);
float f;
iss >> noskipws >> f;
return iss.eof() && !iss.fail();
}
这篇关于从文件中读取花车/字/符号,仅将存储阵列中的C中的彩车++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文