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

时间:2013-06-10 15:01:35

标签: 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

我该如何做到这一点。提前致谢 任何帮助表示赞赏

6 个答案:

答案 0 :(得分:3)

我会做类似以下的事情。不,开个玩笑,我会在现实生活中使用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

答案 1 :(得分:2)

只需使用getline

while (in >> id) {
    if (!getline(in, address)) {
        // (error)
        break;
    }

    // substr from inside the quotes
    addresses[id] = address.substr(1, address.length() - 2);
}

答案 2 :(得分:1)

这不起作用,因为流操作符>>在尝试读取字符串时会将空格作为分隔符。

您可以使用getline(stream, address, '\t');读取具有特定分隔符的字符串。

或者只是getline(stream, address)如果在该行上没有其他内容可读:

long int id;
string address;
myfile >> id;
getline(stream, address);

这只是一个示例,请参阅 @ not-sehe 的完整解决方案的答案(使用getline读取行,然后使用stringstream解析每一行)。

答案 3 :(得分:0)

您可以使用cin.getline()来读取该行的其余部分。

首先读取数字,然后使用getline()读取剩余的数据。

答案 4 :(得分:0)

>>运算符在空格处终止字符串。我建议使用

char temp[100];
myfile.getline(temp,max_length);

这一次读取一行。然后你可以使用循环以你想要的方式分割行。

我想补充一点,您可能需要atoi(char *)(来自模块cytpe.h)函数将整数字符串转换为整数。

答案 5 :(得分:0)

    getline(myfile, address, '"');//dummy read skip first '"'
    getline(myfile, address, '"');
相关问题