如何将字符串与文本文件分开

时间:2014-06-23 00:56:29

标签: c++ string

我有一个文本文件,其信​​息格式如下:

  

id last,first string

例如:

  

0 Snow,John nothing

     

1诺里斯,查克一切

如何获得单独存储的姓氏和名字?

为了从文件中获取信息,我做了:

#include <fstream>

int id;
string str;
string last;
string first;

int main()
{
    ifstream myfile(ex.txt);

    myfile >> id;

    while (myfile)
    {
        for (int i = 0; i < 4; i++) // this is the amount of times i'll get information from 1 line

        {
            id = id; // its actually some_structure.id = id, omit

            getline(myfile, last, ','); // i think i need to use another function as getline get the whole line

            cout << id;

            cout << last; // print out the whole line!

        }

    }

}

4 个答案:

答案 0 :(得分:4)

ifstream myfile;
string line;
while (getline(myfile, line))
{
    istringstream ss(line);
    int id;
    ss >> id;
    string fullname;
    ss >> fullname;
    string firstname, lastname;
    {
        istringstream ss2(fullname);
        getline(ss2, lastname, ',');
        getline(ss2, firstname);
    }
}

答案 1 :(得分:1)

if (std::ifstream input(filename))
{
    int id;
    string lastname, firstname, other_string;
    while (input >> id && getline(input, lastname, ',') &&
           input >> firstname >> other_string)
        ... do whatever you like...
    if (!input.eof())
        std::cerr << "error while parsing input\n";
}
else
    std::cerr << "error while opening " << filename << '\n';

上面的代码比我见过的其他答案有更多的错误检查,但不可否认 - 因为它不会一次读取一行文本然后解析字段,它会很乐意接受,例如:

10 Chuck,
Norris whatever

答案 2 :(得分:0)

会推荐这样的东西:

string name;
myfile >> id >> name >> str;
first = name.substr(0, name.find(","));
last = name.substr(name.find(",") + 1);

请注意,您的EOF检查不正确。

答案 3 :(得分:0)

//完成工作的完整代码 //请删除取消注释所有代码

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () {
    string line;
    ifstream myfile ("ex.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << '\n';
            string last  = line.substr(line.find(" ") + 1, line.find(",") - 2);
            string first = line.substr(line.find(",") + 1, line.find(",") + line.find(" ") - 1); 
        }
        myfile.close();
    }    
    else { 
        cout << "Unable to open file"; 
    }

    return 0;
}