2014-11-07 48 views
1

下面的代码是为了从文件“float.txt”中计算所有浮动数字。问题是浮动数字之间有垃圾信息。为什么浮动输入文件不工作C++

示例文件:

23.5 aujsaN8.2<:::32 

第一浮点后得到,while循环永远不会结束,程序不再从文件的任何信息。请帮忙。

int main() 
{ 
    float num; 
    ifstream input("float.txt"); 

    input >> num; 
    while (!(input.eof())) 
    { 
     input >> num; 
    } 
    input.close(); 

    return 0; 
} 
+0

你想要发生什么? – 0x499602D2 2014-11-07 00:17:43

+0

明显的解决方案是在处理之前清理float.txt。 – 2014-11-07 00:41:21

+1

[不要在循环条件中使用eof](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – 2014-11-07 00:41:42

回答

2

你可以做这样的事情:

decltype(input)::Traits::int_type c; 
while ((c = input.peek()) != decltype(input)::Traits::eof()) 
{ 
    if (std::isdigit(c)) 
    { 
     input >> num; 
     ... use num ... 
    } 
    else 
     input.get(); 
} 

这里的想法是peek下一个字符,如果它是一个数字,然后我们知道>>流至double会成功,否则我们其实get()字符将其从输入流中删除。

,如果你需要提取负数它变得棘手(提示:一个办法 - 用bool跟踪如果看到c的最后一个值是-,然后使用num之前有if (the_bool) num = -num;)。虽然上面的代码处理X0.23X - > 0.23,您可能需要也可能不需要处理X.23X - 如果是的话,请检查.,然后查看下一个字符是否是数字......棘手的是,偷看数字意味着您已经消耗.,所以它不会在那里为input >> num ...你可以尝试input.putback('.'),但我不确定这是标准要求工作时,你已经消耗了一个角色然后偷看 - 你必须检查... 。

+0

@ 0x499602D2:干杯: - )。 – 2014-11-07 00:23:57

+0

即时通讯新手到C++ ...你可以嘲笑我吗? – Machination 2014-11-07 01:13:51

+0

@机器:哪些位?基本上......将'decltype(input):: Traits :: int_type'简化为'int'和'decltype(input):: Traits :: eof()'很可能是'-1' - 传统的' int'表示EOF状态。至于'peek'和'get' - 假设你输入了“A123Z” - 最初'peek()'会返回'A',但是如果你得到(),那么下一个窥视就会看到'1', 'std :: isdigit(c)'将变为'true',然后'input >> num'从流中删除''123''并将'123'放入'num'中,然后下一个'peek()'和'get()'见'Z',然后最后一个'peek()'报告''eof' .... – 2014-11-07 03:35:17

-1

这个作品

// g++ -o parse_float_file parse_float_file.cpp -std=c++11 

#include <iostream> 
#include <fstream> 
#include <string> 

int main() { 

    float curr_number; 
    std::ifstream inFile("float.txt"); 
    std::string line; 

    while(getline(inFile, line)) { 

     try { 

      curr_number = std::stof(line); 

      std::cout << "-->" << curr_number << "<--" << std::endl; 

     } catch (const std::exception &e) { 

      std::cout << "ERROR - not a float : " << line << std::endl; 
     } 
    } 

    return 0; 
} 
+0

读取文件,但不会从其他文本中提取'float'值题.... – 2014-11-07 00:25:01

0

看,我不知道如何声明输入>> NUM;作品我从来没有使用过,而是我会做这些以便从指定的文件中提取花车。

float floats=0; 
char string[100], ch; 
while (file.get(ch)!=' ') 
{ 
string[i]=ch; 
i++; 
} 
string[i]='\0'; 
floats=atof(string); 

这个程序简单地复制字符,直到一个“”(空格)被发现,如文件ü所示,那么函数AOTF()将字符串转换为浮点数。 这是你的问题的答案??如果是的话请投票+1,如果有任何问题你可以问我,我一定会帮你...