Reputation: 1
I don't know why, but my program keeps exiting while loop ( the one inside "if" statement)
the input file contains "abc abb ca" and this should put "abc" and "abb" into one (stack_arr[0]) stack and "ca" into different one ( stack_arr[2])
fin.get(ch);
while (fin)
{
if((int)ch>=97 && (int)ch<=122)
{
x=(int)ch-97;
while(fin && (int)ch>=97 && (int)ch<=122)
{
stack_arr[x].push(ch);
fin.get(ch);
}
}
fin.get(ch);
}
but it only puts all the 'a' in one stack, all the 'b' in another and so on... i found out that in inner while loop it enters, does one cycle, but does not stay. I cannot understand why is it so.
Upvotes: 0
Views: 259
Reputation: 58427
Instead of your current approach you could make use of the STL (after all, you are programming in C++) to create a more sparse structure containing the different strings:
std::ifstream fin("test.txt", std::ios_base::in);
std::map<char, std::vector<std::string>> stack;
std::string token;
while (getline(fin, token, ' ')) {
if (!stack.count(token[0])) {
stack[token[0]] = {};
}
stack[token[0]].push_back(token);
}
fin.close();
// Print the contents
for (auto& e : stack) {
std::cout << "key = " << e.first << "\n";
for (auto& s : e.second) {
std::cout << s << "\n";
}
}
If I run this with the following in test.txt:
abc abb ca
ccb kw
I get the following output:
key = a
abc
abb
key = c
ca
ccb
key = k
kw
Some people might frown at the use of std::map
, and if performance is a major concern then perhaps you should be looking at other classes. I just picked a simple implementation.
Upvotes: 1