从文件中提取数据并将其存储在C ++中的字符串中

时间:2014-01-11 22:43:34

标签: c++ string pointers

我有一个文件,其中包含以下格式的学生记录。

Umar|Ejaz|12345|umar@umar.com
Majid|Hussain|12345|majid@majid.com
Ali|Akbar|12345|ali@geeks-inn.com
Mahtab|Maqsood|12345|mahtab@myself.com
Juanid|Asghar|12345|junaid@junaid.com

数据已按照以下格式存储:

firstName|lastName|contactNumber|email

总行数(记录)不能超过限制100.在我的程序中,我定义了以下字符串变量。

#define MAX_SIZE 100
// other code
string firstName[MAX_SIZE];
string lastName[MAX_SIZE];
string contactNumber[MAX_SIZE];
string email[MAX_SIZE];

现在,我想从文件中提取数据,并使用分隔符“|”,我想将数据放入相应的字符串中。我正在使用以下策略将数据放回字符串变量。

ifstream readFromFile;  
readFromFile.open("output.txt");
// other code
int x = 0;
string temp;

while(getline(readFromFile, temp)) {
    int charPosition = 0;
    while(temp[charPosition] != '|') {
        firstName[x] += temp[charPosition];
        charPosition++;
    }
    while(temp[charPosition] != '|') {
        lastName[x] += temp[charPosition];
        charPosition++;
    }
    while(temp[charPosition] != '|') {
        contactNumber[x] += temp[charPosition];
        charPosition++;
    }
    while(temp[charPosition] != endl) {
        email[x] += temp[charPosition];
        charPosition++;
    }
    x++;
}

是否需要在每个字符串的末尾附加空字符'\ 0'?如果我不附加,当我在程序中实际实现这些字符串变量时,它是否会产生问题。我是C ++的新手,我已经提出了这个解决方案。如果有人有更好的技术,他肯定会受到欢迎。

编辑:我也无法将char(acter)与endl进行比较,我该怎么办?

编辑:我写的代码不起作用。它给了我以下错误。

     Segmentation fault (core dumped)

注意:我只能使用.txt文件。无法使用.csv文件。

2 个答案:

答案 0 :(得分:4)

有很多技巧可以做到这一点。我建议在“[C ++]读取文件”中搜索StackOveflow以查看更多方法。

查找和子串
您可以使用std::string::find方法查找分隔符,然后使用std::string::substr返回位置和分隔符之间的子字符串。

std::string::size_type position = 0;
positition = temp.find('|');
if (position != std::string::npos)
{
    firstName[x] = temp.substr(0, position);
}

答案 1 :(得分:2)

如果不终止带有空字符的C样式字符串,则无法确定字符串的结束位置。因此,您需要终止字符串。

我会亲自将数据读入std::string个对象:

std::string first, last, etc;
while (std::getline(readFromFile, first, '|')
    && std::getline(readFromFile, last, '|')
    && std::getline(readFromFile, etc)) {
    // do something with the input
}

std::endl是一个作为函数模板实现的操纵器。您无法将char与之进行比较。也几乎没有理由使用std::endl因为它在添加换行符后刷新流,这使得写入非常慢。您可能想要与换行符进行比较,即与'\n'进行比较。但是,由于您使用std::getline()读取字符串,因此行中断字符已被删除!您需要确保不会访问超过temp.size()个字符。

您的记录还包含字符串数组而不是字符数组,您可以为它们分配单独的char。您要么想char something[SIZE],要么存储字符串!