我想知道如何读取这个输入文件并存储它:
Tulsa
129.50
Santa Fe
70.00
Phoenix
110.00
San Diego
88.50
Yakama
150.25
这是我的cpp
#include <iostream>
#include "q2.h"
#include <string>
#include <fstream>
using namespace std;
int main()
{
fstream in( "q2input.txt", ios::in );
string loc;
double price;
while(fin >> loc >> price)
{
cout << "location: " << loc<< endl;
cout << "price: " << price << endl;
}
return 0;
}
问题是它只读取前两行。我知道阅读的语法就好像它被分成列一样,但不是这样的。
最佳答案
读取字符串在第一个空格处停止。即阅读Stanta Fe
进入字符串在 Santa
之后停止。如Fe
不是有效的浮点值读数则失败。
该问题至少有两种解决方案:
- 而不是阅读
std::string
使用operator>>()
你会使用std::getline()
使用std::ws
跳过空格后(关于如何正确执行此操作有很多重复的问题)。 - 您将使用不考虑
' '
的流作为空白imbue()
正在寻找合适的std::ctype<char>
方面。这是一个更有趣、更非传统的问题解决方案。
鉴于教师不太可能在没有解释的情况下接受该解决方案,似乎可以为第二种方法提供代码:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <locale>
#include <string>
struct ctype_table {
std::ctype_base::mask table[std::ctype<char>::table_size];
template <int N>
ctype_table(char const (&spaces)[N]): table() {
for (unsigned char c: spaces) {
table[c] = std::ctype_base::space;
}
}
};
struct ctype
: private ctype_table
, std::ctype<char>
{
template <int N>
ctype(char const (&spaces)[N])
: ctype_table(spaces)
, std::ctype<char>(ctype_table::table)
{
}
};
int main()
{
std::ifstream in("q2input.txt");
in.imbue(std::locale(std::locale(), new ctype("\n\r")));
std::string name;
double value;
while (in >> name >> value) {
std::cout << "name='" << name << "' value=" << value << "\n";
}
}
关于c++ - 如何从文本文件读取字符串和 double 到链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011172/