c++ - C++从文件中读取格式化数据

标签 c++ file-io

我正在尝试编写代码以从文件中读取数据。该文件如下所示:

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/

相关文章:

c++ - 使用重载下标运算符 “[ ]” 获取和设置数组的值将不起作用

c++ - 如何在 KeyEventArgs...VC++2010 中一起处理两个函数?

android - 从文件中检索 JSONObject

python - 需要一种方法来确定文件是否已写入

java - java源码最终是如何与文件交互的?

file - 将 NSData 写入文件的最简单方法

c - 如何将文本文件读入结构并与其成员交互?

c++ - 从 C++ 中的 3D 矩阵中提取 2D 矩阵

c++ - 我的信号量(来自 Boost 的 named_semaphore)做错了什么?

c++ - 没有匹配的函数来调用 - Xcode?