为什么我无法从字符串流中读取一些单词后跟整数的整数?



我是C++的初学者,只是想知道为什么我不能在输出的第二行显示6.9
我是不是忽略了"女士"这个词,然后在循环时中断getline,然后转到另一行?

#include <iostream>
#include <sstream> 
#include <string>
#include <fstream>
using namespace std; 

int main() {
ifstream input("Text.txt");
ofstream output("Text1.txt");
string line; 
while (getline(input, line)) {
istringstream inputstring(line);
double result;
string garbage;
while (inputstring >> garbage) {
inputstring.ignore();
if (inputstring >> result) {
output << result << endl;
}
}
}
}

这是我的text.txt 内容

broccoli 2.95  
lady finger 6.9  
Watermelon 10  
Apple 7.8  
Orangw 8.5  

这是输出

2.95  
10  
7.8  
8.5  

首先阅读"女士;进入garbage,然后你ignore后面的单个空格字符,然后你试着读";手指;则result失败并且流进入错误状态
然后循环退出,因为流出错。

当数字输入失败时,您需要清除错误状态,并且不需要ignore任何内容。

while (inputstring >> garbage) {
if (inputstring >> result) {
output << result << endl;
}
else {
// This will make the stream re-read the non-number as a string.
inputstring.clear();
}
}

您发现输入很难。问题是你的前导文本可能有空格。你不知道有多少。

正确的思考方式是认识到数字是始终行上的最后一个项。

如果我们改变我们的观点,生活会变得越来越容易。有无数种方法可以从一行文本中分割出最后一项。一个简单的方法是将行标记化(通过在空白处进行拆分(:

#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::istringstream inputstream( R"<>(
broccoli 2.95
lady finger 6.9
Watermelon 10
Apple 7.8
Orangw 8.5
)<>" );

// For each non-blank line:
std::string line;
while (getline( inputstream >> std::ws, line ))
{
// Tokenize the line and keep only the last token found
std::istringstream tokenstream( line );
std::string token;
while (tokenstream >> token) { }

// The last token should be your number
try 
{
double number = stod( token );
std::cout << number << "n";
}
catch (...) { }
}
}

这样思考的好处是,如果你的输入包括像这样的哑弹,它也不会那么脆弱

pi
3.141592
i 8 8 pickles

当然,所有这些都假定您不关心文本⟷数字关系:所有重要的是有效的数字(因为你正在对它们求和或诸如此类(。

相关内容

最新更新