【发布时间】:2014-04-14 16:53:54
【问题描述】:
如何从文件中读取行并将该行的特定段分配给结构中的信息?以及如何在空行处停止,然后再继续直到到达文件末尾?
背景:我正在构建一个程序,它将获取一个输入文件,读入信息,并使用双散列将该信息放入哈希表的正确索引中。
假设我有这个结构:
struct Data
{
string city;
string state;
string zipCode;
};
但文件中的行格式如下:
20
85086,Phoenix,Arizona
56065,Minneapolis,Minnesota
85281
56065
我似乎无法弄清楚这一点。我很难阅读文件。第一行基本上是要构建的哈希表的大小。下一个空行应该被忽略。然后接下来的两行是应该进入结构并散列到散列表中的信息。然后应该忽略另一个空白行。最后,最后两行是需要匹配的输入,以查看它们是否存在于哈希表中。所以在这种情况下,没有找到 85281。虽然找到了 56065。
这就是我所拥有的,但它似乎并没有做我想做的事:
int main(int argc, char *argv[])
{
string str;
//first line of file is size of hashtable
getline(cin, str);
stringstream ss(str);
int hashSize;
ss >> hashSize;
//construct hash table
Location *hashTable = new Location[hashSize];
//skip next line
getline(cin, str);
string blank = " ";
while(getline(cin, str))
{
{
//next lines are data
Location locate;
string line;
getline(cin, line);
istringstream is(line);
getline(is, locate.zipCode, ',');
getline(is, locate.city, ',');
getline(is, locate.state, ',');
insertElementIntoHash(hashTable, locate, hashSize);
}
}
dispHashTable(hashTable, hashSize);
//read third set of lines that check if the zipCodes are in the hashtable or not
while(getline(cin, str))
{
//stop reading at a blank line or in this case, end of file
stringstream is(str);
string searchZipCode;
is >> searchZipCode;
searchElementInHash(hashTable, hashSize, searchZipCode);
}
//delete hash table after use
delete []hashTable;
return 0;
}
【问题讨论】:
-
你过得有多辛苦?请展示什么不起作用。
-
提示:while(getline(cin, str) && (str != ""))
-
@AbhishekBansal 这是一个不好的提示
-
@AbhishekBansal 我试过了,我想它让它工作得更好一点,但仍然有很多问题。有人可以给我一个直截了当的答案吗?我真的很想了解如何使用 getline 和 istringstream。