如何逐行读取,拆分字符串

问题描述 投票:-1回答:3

我希望能够逐行浏览这个文本文件并抓住它的一部分。例如,

Albert, Fred
4541231234
8888 Avenue Drive

Doe, John
6191231234
1234 State Street

Smith, Mike
8791231234
0987 Drive Avenue

我需要抓住阿尔伯特并将其存储为姓氏。弗雷德作为名字(不包括“,”,以及电话号码和地址。

通过线程搜索,我找到了一些帮助,这就是我所拥有的。

void AddressBook::readFile(Contact * phoneBook[])
{

    std::string line, line1, line2, line3, line4;
    std::ifstream myFile("fileName.txt");
    std::string name, fName, lName, phoneNumber, address;

    if (!myFile.is_open())
    {
        std::cout << "File failed to open." << std::endl;
        return;
    }

    while (true)
    {
        if (!getline(myFile, line1)) 
        {
            break;
        }

        if (!getline(myFile, line2)) //need to parse into lName and fName
        {
            break;
        }

        if (!getline(myFile, line3))
        {
            break;
        }

        if (!getline(myFile, line4))
        {
            break;
        }

        addContact(line1, line2, line3, line4);
    }
}

如您所见,此代码仅占用整行。如何在逗号处停止,将其存储到姓氏变量中,并继续使用第一个名称?

c++
3个回答
1
投票

你错过了一个delimiter

从is中提取字符并将它们存储到str中,直到找到分隔字符delim(或换行符,'\ n',for(2))。

getline()在C ++中重载,所以你可以像你一样使用它,或者你可以像这样使用它:

getline(myFile, line1,',')

这将告诉getline使用换行符作为分隔符,而不是空格。


1
投票

std::getline has an overload with a third parameter允许您在要使用的任何字符上分割流而不是行结尾。所以你拿line1,用它作为std::istringstream的基础

std::istringstream strm(line1);

然后你就可以了

std::getline(strm, lastname, ','); 

这会留下一个空格,然后是流中的名字,忽略空格和getline到流的末尾以获取名字。

总之,它应该看起来像

std::istringstream strm(line1);
std::getline(strm, lastname, ','); 
strm.ignore();
std::getline(strm, firstname); 

1
投票

我想你可以使用substr函数,就像那样:

line2_1 = line2.substr(0, line2.find(','))
line2_2 = line2.substr(line2.find(',')+2, line2.length())

+2是因为你有一个逗号(+ 1)和逗号后的空格(+1)。

© www.soinside.com 2019 - 2024. All rights reserved.