0

我有一个包含一个 int 和两个字符串的结构。读取文件时,前两个值以逗号分隔,最后一个值以换行符终止。然而,第三个参数可能是空的。

前数据:7, john doe, 123-456-7891 123 fake st.

我想这样做,以便我的程序将获取第一个数字并将其放入 int,找到逗号并将第二个数字放入结构的字符串等。

第一个问题是我应该改用一个类吗?我见过,getline(stream, myString, ',');但我的论点是不同的数据类型,所以我不能把它们都扔进一个向量中。

我的代码:

struct Person{
    int id;//dont care if this is unique 
    string name;
    string extraInfo;
};

int main(int argc, char* argv[]){
    assert( argc ==2 && "Invalid number of command line arguments");
    ifstream inputFile (argv[1]);
    assert( inputFile.is_open() && "Unable to open file");
}

存储此信息并从前两个逗号分隔并以换行符结尾的文件中检索它的最佳方法是什么?我还希望程序忽略文件中的空行。

4

3 回答 3

1

我会使用 normal 逐行读取文件getline()。然后,将其放入 astringstream中进行进一步解析或使用string'sfind()函数手动拆分文本。

还有一些注意事项:

  • 我不明白你关于使用课程的第一个问题。如果你的意思是 for Person,那么答案是没关系。
  • 对你无法控制的东西使用 assert 是错误的,比如 argc。这应该只用于验证您没有犯编程错误。此外,如果你#define NDEBUG,断言都消失了,所以它们不应该真正成为你的程序逻辑的一部分。改为抛出 std::runtime_error("未能打开文件") 。
  • 您可能不希望字符串中出现双引号。此外,您可能"a,b"不希望被逗号分隔。确保您有断言所需功能的测试。
于 2013-05-21T03:07:34.197 回答
0

您仍然可以使用该getline方法标记一行,但您首先必须阅读该行:

vector<Person> people;
string line;
int lineNum = 0;

while( getline(inputFile, line) )
{
    istringstream iss(line);
    lineNum++;

    // Try to extract person data from the line.  If successful, ok will be true.
    Person p;
    bool ok = false;

    do {
        string val;
        if( !getline(iss, val, ',') ) break;
        p.id = strtol( val.c_str(), NULL, 10 );

        if( !getline(iss, p.name, ',') ) break;
        if( !getline(iss, p.extraInfo, ',') ) break;

        // Now you can trim the name and extraInfo strings to remove spaces and quotes
        //[todo]

        ok = true;
    } while(false);

    // If all is well, add the person to our people-vector.
    if( ok ) {
        people.push_back(p);
    } else {
        cout << "Failed to parse line " << lineNum << ": " << line << endl;
    }
}
于 2013-05-21T03:07:44.827 回答
0

使用 getline 获取字符串中的行后,使用 strtok。

char myline[] = "7, john doe, 123-456-7891 123 fake st.";
char tokens = strtok(myline, ",");
while(tokens)
{
    //store tokens in your struct values here
}

您需要包括#include <string.h>使用 strtok

于 2013-05-21T06:05:12.030 回答