-3

I have a file called fruit.txt like this

apple 2 in place A
banana 3 in place B
peach 4 in place C

what is the total?

then I want to use c++ to read this file line by line but I only want the fruit name and number and omit other information. For example, the first line, I want to read "apple" and write into string name[i] and read 2 and write into int num[i] and omit the "in place A". Keep this process until the end but also omit the last line "what is the total". The following headers are allowed: <iostream>, <fstream>, <sstream>, <iomanip>, <string>, <cstdlib>.

So how to implement this in C++?

  • 2
    From http://stackoverflow.com/help/on-topic Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it – paisanco Jun 22 '15 at 04:47
  • 1
    What simpler problem have you already solved? – Beta Jun 22 '15 at 04:50
  • 1
    You really didn't ask a question. You can't just describe the thing you're trying to do and ask how to do it. You have to ask a *specific* question. Have you worked out an algorithm yet? If not, ask about the specific issue you're having doing that. If you have, then show it to us and ask us about the specific issue you're having implementing it. But "this is what I'm trying to do" just isn't a question. – David Schwartz Jun 22 '15 at 05:14
  • I'm voting to close this question as off-topic because this is a homework problem and the user has shown no effort to solve it. – R Sahu Jun 22 '15 at 15:07

2 Answers2

0

you could use std::getline to store each line into a string. For each line, create a string stream that reads from the line. Use the >> operator twice to get the first two 'tokens' which is the string and number (>> reads until space) Read C++ documentation and old stack overflow questions if you need to learn how to use stringstream and getline

js sol
  • 19
  • 2
  • Yes I get the whole line and store it in a string, but I don't know how to use >> twice to read it. Could you give an example that how to do it? – techmagician Jun 22 '15 at 05:03
  • if you create a std::istringstream called, say, `linereader` it would look something like this: `int num; string fruit; linereader >> fruit >> num;` – js sol Jun 22 '15 at 23:41
0

Here is a code snippet expanding on @js-sol's answer

  std::string line;
  while (std::getline(infile, line)) {

    std::istringstream ss(line);

    std::string name;
    int num;

    ss >> name >> num;

    // do something with name and num                                                                                                                          

  }

Edit: I think, your question is similar to this: Read file line by line

Community
  • 1
  • 1
ssemilla
  • 3,900
  • 12
  • 28