我正在尝试编写代码以从文件中读取数据。该文件如下所示:
47012 "3101 E 7TH STREET, Parkersburg, WV 26101"
48964 "S16 W22650 W. LINCOLN AVE, Waukesha, WI 53186"
.
.
.
.
我需要将数字存储为 int,将地址存储为字符串。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("input.txt");
long int id;
string address;
myfile >> id;
cout << id << endl;
myfile >> address;
cout << address.c_str() << endl;
myfile.close();
system("pause");
return 0;
}
程序输出
47012
"3101
我需要的输出是
47012
3101 R 7TH STREET, Parkersburg, WV 26101
我该怎么做。提前致谢 感谢任何帮助
最佳答案
我会做类似下面的事情。不,开玩笑,我会在现实生活中使用 Boost Spirit。但是,这似乎也可以尝试使用标准库方法:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream myfile("input.txt");
std::string line;
while (std::getline(myfile, line))
{
std::istringstream linereader(line, std::ios::binary);
long int id;
linereader >> id;
if (!linereader)
throw "Expected number";
linereader.ignore(line.size(), '"');
string address;
if (!std::getline(linereader, address, '"'))
throw "Expected closing quotes";
cout << id << endl << address << endl;
}
myfile.close();
}
打印:
47012
3101 E 7TH STREET, Parkersburg, WV 26101
48964
S16 W22650 W. LINCOLN AVE, Waukesha, WI 53186
关于c++ - C++从文件中读取格式化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026926/