簡體   English   中英

在C ++中從文件讀取格式化的數據

[英]Reading formatted data from file in C++

我正在嘗試編寫代碼以從文件讀取數據。 該文件如下所示:

47012   "3101 E 7TH STREET, Parkersburg, WV 26101"
48964   "S16 W22650 W. LINCOLN AVE, Waukesha, WI 53186"
.
.
.
.

我需要將數字存儲為整數,並將地址存儲為字符串。

#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

只需使用getline

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

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

這不起作用,因為在嘗試讀取字符串時,流運算符>>將空格作為定界符。

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

或者如果該行上沒有其他要讀取的內容,則只需簡單地獲取getline(stream, address)即可:

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

這只是一個示例,請參見@ not-sehe的答案以獲取完整的解決方案(使用getline讀取各行,然后使用stringstream解析每一行)。

您可以使用cin.getline()來讀取該行的其余部分。

首先讀取數字,然后使用getline()讀取剩余的所有內容。

>>運算符在空格處終止一個字符串。我建議使用

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

這一次讀取一行,然后您可以使用循環以所需的方式拆分行。

我想補充一點,您可能需要atoi(char *) (來自cytpe.h模塊)函數將整數字符串轉換為整數。

    getline(myfile, address, '"');//dummy read skip first '"'
    getline(myfile, address, '"');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM