1

I need simple program in C++ that will open text file and going line by line find second argument by knowing first in list.

Content of text file:

1, red
2, blue
3, green
4, orange

So I need a program that will go line by line and each line turn into array ( of two elements ) and then compare first element with user interactively inserted number.

So if user insert 2, it goes line by line, comparing first element of array-ed line and if it matches, it prints second element in array ( blue ), and if user type 3, it prints green...

I have always working in PHP, and it's much easier than this, so I am stuck a little bit with this now... :/

SharkTheDark
  • 3,089
  • 4
  • 24
  • 29
  • Does it matter? This should be simple for someone who knows C++, but I don't... – SharkTheDark Jul 05 '11 at 10:28
  • 7
    Yes, it does matter! SO is not a "write me some code" service, it's a question-and-answer site. If you start by telling us what you've tried so far and why it didn't work, we can suggest specific improvements. – Oliver Charlesworth Jul 05 '11 at 10:29
  • Okay then... Q1: How do you open text file in C++ ? Q2: How do you read file line by line? Q3: How do you turn string with "," into array based on that delimiter? – SharkTheDark Jul 05 '11 at 10:31
  • 1
    Q1, Q2: C++ Input/Output with files: http://www.cplusplus.com/doc/tutorial/files/ – Igor Jul 05 '11 at 10:34
  • 1
    Q3: http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – Igor Jul 05 '11 at 10:35
  • Why do you need it in C++? This looks like a trivial job for `awk` or `join` and - heck - you can even use php script from the command line ... – sehe Jul 05 '11 at 10:54
  • Additionally I'd suggest that you get a [book (No 2 - Accelerated C++)](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to get you up to speed fast. – Fabio Fracassi Jul 05 '11 at 11:42

3 Answers3

5

Here you go:

#include <iostream>
#include <fstream>
#include <map>
#include <sstream>

int main(int argc, char* argv[]) {
  if (argc != 2) {
    std::cerr << "Usage: test [inputfile]" << std::endl;
    return 1;
  }
  std::fstream stream(argv[1]);
  if (!stream.good()) {
    std::cerr << "Error: could not open file: " << argv[1] << std::endl;
    return 2;
  }
  std::string line;
  std::map<int, std::string> map;
  while (std::getline(stream, line)) {
    std::string::size_type pos = line.find(',');
    std::stringstream sstream(line.substr(0, pos));
    int index;
    sstream >> index;
    map[index] = line.substr(pos+2);
  }
  int in;
  while (std::cin >> in) {
    std::map<int, std::string>::iterator i = map.find(in);
    if (i == map.end())
      std::cerr << "index not found" << std::endl;
    else
      std::cout << i->second << std::endl;
  }
  return 0;
}
Markus Pilman
  • 3,104
  • 3
  • 22
  • 31
  • 1
    quoting Oli Charlesworth: SO is not a "write me some code" service – Igor Jul 05 '11 at 10:50
  • Is it unhelpful, disturbing or wrong? Or what exactly is the reason for voting down? Behavior like this makes people not answering any questions anymore... – Markus Pilman Jul 05 '11 at 11:01
  • 2
    it is unhelpful, because the OP won't learn much from presenting him a complete solution (and the problem in itself is so trivial that it is only suitable for learning). Making him think about what his real questions are (and answering those) is much more useful. – Fabio Fracassi Jul 05 '11 at 11:36
  • 2
    I've had a similar question and this post in fact was helpful. Lets let those who have questions decide what is helpful and what isn't rather than getting them them conform to whatever educational theories we subscribe to. If someone is willing to take the time to "write me some code", helpful code in fact, they should be commended for it. Not saying that guiding people to find answer on their own line by line is a bad approach, but it's not the only "correct" one. – alex28 Jul 05 '11 at 19:58
2

Q1: How do you open text file in C++ ? Q2: How do you read file line by line?

C++ Input/Output with files

Q3: How do you turn string with "," into array based on that delimiter?

How to split a string in C++?

Community
  • 1
  • 1
Igor
  • 26,650
  • 27
  • 89
  • 114
1

This is probably not helpful, except for me; I get to practice using Spirit parsing (and karma output generation as a bonus):

#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <fstream>
#include <map>

namespace qi = ::boost::spirit::qi;
namespace karma = ::boost::spirit::karma;

typedef std::map<int, std::string> index_t;

index_t read_index(const char* filename)
{
    using boost::spirit::istream_iterator;
    using namespace qi;

    index_t result;
    std::ifstream ifs(filename);
    ifs.unsetf(std::ios::skipws);
    istream_iterator begin(ifs), end;

    if (!parse(begin, end, (int_ >> omit[lit(',') >> *char_(" \t")] >> *(char_ - eol)) % eol, result))
    {
        throw std::runtime_error("Unable to read/parse index file ");
    }

    return result; // http://en.wikipedia.org/wiki/Return_value_optimization
}

int main()
{
    index_t index = read_index("input.txt");

    using namespace karma;
    std::cout << format(('[' << int_ << ": " << *char_ << ']') % eol, index) << std::endl;

    for (int i=0; i<10; i++)
    {
        int lookup=rand()%6;
        std::cout << "Random lookup: " << lookup << ": " << index[lookup] << std::endl;
    }

    return 0;
}

Oh, sample output:

[1: red]
[2: blue]
[3: green]
[4: orange]
Random lookup: 1: red
Random lookup: 4: orange
Random lookup: 3: green
Random lookup: 1: red
Random lookup: 5: 
Random lookup: 1: red
Random lookup: 4: orange
Random lookup: 0: 
Random lookup: 3: green
Random lookup: 1: red
sehe
  • 374,641
  • 47
  • 450
  • 633